Sub topic 1
What a module is
A module is the unit Python uses to organize code. Every import statement you write gives you a module. This chapter separates two things that are easy to mix up: the file on disk that defines a module, and the module object that exists while your program runs. Later chapters build on this distinction.
Prerequisites
This chapter assumes you can:
- Write Python functions, classes, and variables.
- Run a script from a terminal with
python file.py. - Navigate directories and know which directory your terminal is currently in.
You do not need to know how import works internally. This chapter introduces the term only as far as it is needed.
A module is an object, not a file
Most Python tutorials say "a module is a .py file". That is a useful first approximation, but it is incomplete. A file is stored on disk and does nothing by itself. A module is an object in memory, an instance of the built-in type module. Python builds that object by reading the file and running its code.
This distinction explains behavior that otherwise looks odd:
- Editing the file does not change a module that is already loaded.
- Changing an attribute on the module object does not change the file.
- Some modules have no file at all, such as built-in modules written in C or modules created on the fly.
Here is a small file to work with.
# temperature.py
"""Helpers for converting temperatures."""
FREEZING_C = 0
def c_to_f(celsius):
return celsius * 9 / 5 + 32Now a second file in the same directory imports it and inspects the result.
# main.py
import temperature
print(type(temperature))
print(temperature.__name__)
print(temperature.__doc__)
print(temperature.c_to_f(100))
print(temperature.FREEZING_C)Running python main.py prints:
<class 'module'>
temperature
Helpers for converting temperatures.
212.0
0The name temperature in main.py refers to a module object. Its __name__ comes from the file name without .py. Its __doc__ is the string at the top of the file. The constant and the function are attributes of the object.
What a module contains
When Python runs a module's file, every top-level assignment, def, class, and import creates a name. Those names are stored on the module object as attributes. Python also adds several attributes of its own.
| Attribute | Meaning |
|---|---|
| `__name__` | The module's name, such as `temperature`. |
| `__doc__` | The module docstring, or `None`. |
| `__file__` | Path of the source file. Missing for built-in modules. |
| `__spec__` | A record of how the module was found and loaded. `None` for modules built by hand. |
| `__dict__` | The dictionary that stores all of the module's names. |
The __dict__ attribute is the key to everything else. A module's attributes are just entries in a dictionary, so temperature.FREEZING_C is a lookup of the key "FREEZING_C" in temperature.__dict__. You can list a module's names with dir(temperature) or vars(temperature).
A module is a namespace
A namespace is a mapping from names to objects. The module object gives your code a namespace of its own. If temperature.py defines a variable called result and your script also defines result, the two do not collide. One is result in your script, and the other is temperature.result.
This is the main practical reason modules exist. They let you split a program into pieces that each manage their own names. Inside a module, a top-level name is a global variable, but "global" means global to that module only. Python has no program-wide global namespace for your own code.
Changing the object does not change the file
Because the module is an object, you can modify it at runtime.
import temperature
temperature.FREEZING_C = -5
print(temperature.FREEZING_C)
print(temperature.c_to_f(0))The first line prints -5. The file temperature.py on disk is unchanged. Any other part of the same program that imports temperature also sees -5, because all of them share one module object. Python loads a module once per process and reuses it. The next chapters explain the mechanism and the cache behind it.
Assigning to a module's attributes from outside is legal, but it is a common source of confusing bugs. Treat module attributes as read-only unless the module is designed for configuration.
Modules that have no file
Because a module is just an object, you can make one without any file. The standard types module provides the constructor.
import types
scratch = types.ModuleType("scratch")
scratch.answer = 42
exec("def double(x):\n return x * 2", scratch.__dict__)
print(scratch.answer)
print(scratch.double(21))
print(getattr(scratch, "__file__", None))
print(scratch.__spec__)This prints:
42
42
None
NoneThe exec call runs a string of code with the module's dictionary as its namespace. That is, in simplified form, what Python does when it loads a real file. Hand-built modules are rare in application code, but they show that "module" means "object with a dictionary of names". It does not mean "file".
Other modules have files that are not Python source. Built-in modules such as sys are compiled into the interpreter and have no __file__. Extension modules are compiled shared libraries, and their __file__ ends in .so or .pyd.
Module names must be identifiers
The import statement takes a name, not a path. The name must be a valid Python identifier, so the file name has to follow the same rules.
temperature.pycan be imported astemperature.my-tools.pycannot be imported withimport my-tools, because the hyphen is parsed as subtraction.2fast.pycannot be imported, because identifiers cannot start with a digit.
Use lowercase names with underscores, as in unit_conversion.py. This follows the PEP 8 style guide. Short, descriptive, lowercase names also avoid problems on case-insensitive file systems, where Temperature.py and temperature.py look identical to the operating system but not to Python.
Inspecting any module
When you are unsure what a module is or where it came from, three checks answer most questions.
import json
print(json.__name__)
print(json.__file__)
print(sorted(name for name in vars(json) if not name.startswith("_"))[:5])The first line shows the name Python uses. The second shows the file it loaded, which is the quickest way to discover that you imported the wrong one. The third lists a few public names. The exact path printed for __file__ depends on your installation.
Common mistakes
- Thinking a file runs every time you import it. It runs the first time only. Later imports reuse the existing module object.
- Confusing the file name with the attribute name.
import temperaturebinds the nametemperaturein your namespace. The file's.pyextension is never part of the name. - Expecting edits to show up immediately. A running interpreter keeps the old module object until it restarts or the module is explicitly reloaded.
- Treating
__file__as always present. Built-in and hand-built modules lack it, so usegetattr(module, "__file__", None)in code that must handle any module.
Exercise
You run import temperature in a program, then edit temperature.py to change FREEZING_C from 0 to 4 while the program is still running, and read temperature.FREEZING_C again. What value do you see, and why? What would you see if your code had first run temperature.FREEZING_C = -5, and the file still said 0 when the program started?
Show answer
In the first case you still see 0. The module object was built from the file once, and the object is what your program reads. Editing the file does not update an object that is already in memory. In the second case you see -5, because assigning to the attribute changes the module object's __dict__ and never touches the file.
Exercise
Create a module object named "config" without any file, give it an attribute DEBUG set to True, and print whether it has a __file__ attribute.
Show answer
Use types.ModuleType. For example: import types, then config = types.ModuleType("config"), then config.DEBUG = True, then print(hasattr(config, "__file__")). The last line prints False, because a hand-built module has no source file.