After this lesson you can move code into its own file, import it from another file, and write modules that are safe to both run and import.
Why modules
As a program grows, one file becomes hard to read. A module is just a Python file. By moving related functions into their own files you get smaller, named pieces that can be reused in several programs. The standard library is a large collection of such modules, and the next lessons cover it.
Your first module
Here is a small module for a shop. Save this as shop_utils.py:
#file: shop_utils.py
TAX_RATE = 0.18
def add_tax(amount):
return round(amount * (1 + TAX_RATE), 2)
def format_price(amount):
return f"Rs {amount:,.2f}"In the same folder, you can now use it from another file, or from the interactive prompt, with import:
import shop_utils
print(shop_utils.TAX_RATE)
print(shop_utils.add_tax(100))
print(shop_utils.format_price(1234.5))0.18
118.0
Rs 1,234.50After a plain import, the module's names are kept inside the module object, so you reach them with a dot. This keeps your program tidy: you can always see where a function came from.
Importing specific names
If you use one function often, bring it in directly with from ... import:
from shop_utils import add_tax, format_price
print(format_price(add_tax(250)))Rs 295.00Now the names are used without the prefix. The trade-off is that the origin is less obvious when a file grows. A third form renames what you import:
import shop_utils as su
from shop_utils import TAX_RATE as rate
print(su.add_tax(200))
print(rate)236.0
0.18Aliases are mostly used for long module names. There is also from shop_utils import *, which pulls in everything. Avoid it, because you can no longer tell where a name came from, and it may silently overwrite your own names.
What import really does
The first time Python sees import something, it finds the file, runs it from top to bottom, and stores the resulting module object. You can prove that the file runs with a module that prints something:
#file: noisy.py
print("noisy.py is being loaded")
VALUE = 42import noisy
import noisy
print(noisy.VALUE)noisy.py is being loaded
42The message appears once, even though the module was imported twice. Python keeps a cache of loaded modules and reuses it. This also means top-level code in a module should be quick and free of surprises.
The name guard
Every module has a built-in variable called __name__. When the file is imported, it holds the module's name. When the file is run directly, it holds the string "__main__". That lets one file act as both a library and a program.
#file: price_tool.py
def double(amount):
return amount * 2
if __name__ == "__main__":
print("running directly")
print(double(21))Run it directly from a terminal:
python3 price_tool.pyrunning directly
42Now import it instead:
import price_tool
print(price_tool.__name__)
print(price_tool.double(5))price_tool
10The test code inside the if block did not run on import. Without the guard, simply importing the module would have printed the test lines every time. Put demonstrations and the program's entry point under the guard.
How Python finds a module
When you write import shop_utils, Python looks through a list of folders called sys.path, in order. The first entry is the folder of the script you ran, followed by the standard library and installed packages. If no file matches, you get an error:
import shop_utilzModuleNotFoundError: No module named 'shop_utilz'Two practical consequences follow. First, keep your modules next to your script or in a package (see the lesson on packages). Second, never name your own file after a standard module. A file called random.py or json.py in your folder would be found first, and import random would load your file instead of the real one.
Looking inside a module
The built-in dir() lists the names a module defines, and help() shows docstrings. You can filter out the internal double-underscore names:
print([name for name in dir(shop_utils) if not name.startswith("__")])['TAX_RATE', 'add_tax', 'format_price']Modules can hold anything
A module is not limited to functions. It can hold constants, classes and data, and Python treats a variable defined in a module as shared by everyone who imports it. That makes a module a convenient place for settings:
#file: settings.py
SHOP_NAME = "Corner Shop"
OPENING_HOURS = (9, 18)import settings
print(settings.SHOP_NAME)
print(settings.OPENING_HOURS)Corner Shop
(9, 18)Because the module is cached, every file that imports settings sees the same values. Keep such modules small and plain. Putting a lot of logic into a settings file makes it hard to understand what happens at import time.
Common mistakes
- Saving the module under a name that clashes with a standard module, such as
random.pyoremail.py. - Forgetting the module prefix after a plain
import. Writingadd_tax(100)afterimport shop_utilsraises a NameError. - Importing from a different folder than you expected. The folder you start Python in matters.
- Editing a module and not seeing the change in an open interactive session. The module is cached, so restart Python.
- Using
from x import *in real code. - Putting a hyphen in a module name. A file called
shop-utils.pycannot be imported with a normal import. Use underscores.
Exercise
Create a module greetings.py with a function welcome(name) that returns "Welcome, <name>!". Add a __name__ guard that prints the welcome for "Test" only when the file is run directly. Then import the function from another file.
Show one possible answer
#file: greetings.py
def welcome(name):
return f"Welcome, {name}!"
if __name__ == "__main__":
print(welcome("Test"))from greetings import welcome
print(welcome("Asha"))Welcome, Asha!Key points
- A module is simply a .py file. Importing it runs the file once and gives you access to its names.
- import shop_utils keeps names behind the module name. from shop_utils import add_tax brings a name in directly. import ... as gives a shorter alias.
- Python caches imported modules, so a second import does not run the file again.
- Python searches the folder of the running script, then the installed packages, so a module name must not clash with a standard one.
- Wrap script-only code in if __name__ == '__main__': so that importing the file does not run it.