Python Writing Your Own Module
What you will learn
- That every
.pyfile is a module - Importing your own module
- What
__name__is and theif __name__ == "__main__":guard - Running a module with
python -m - Docstrings and private names in modules
- Traps: shared state, circular imports, name clashes
1. Any file is a module
To make a module, simply save functions and variables in a .py file. Create geometry.py:
"""Small geometry helpers."""
PI = 3.14159
def circle_area(r):
"""Return the area of a circle with radius r."""
return PI * r ** 2
def rect_area(w, h):
return w * h
Now another file in the same folder, main.py, can import it by the file name without .py:
import geometry
from geometry import rect_area
print(geometry.circle_area(2))
print(rect_area(4, 5))
print(geometry.__name__, "|", geometry.__doc__)
12.56636
20
geometry | Small geometry helpers.
- The module name is the file name:
geometry.pybecomesgeometry. Use lower-case letters, digits and underscores, and no spaces or hyphens (my-tools.pycannot be imported). - The string at the top of the file is the module docstring, available as
geometry.__doc__and shown byhelp(geometry). - Python finds
geometrybecause it looks in the folder of the running script first (lesson 16.4 explains the full search).
Run main.py with python main.py from that folder.
Quick check: which file name could not be imported as a module: `tools.py`, `my_tools.py` or `my-tools.py`?
my-tools.py: the hyphen is not allowed in a name.
2. Code runs at import time
When Python imports a module, it runs the file from top to bottom (once, lesson 16.1). Definitions create functions; any other statement runs too. Add a print line to geometry.py:
print("geometry module is being loaded; __name__ =", __name__)
Running main.py now shows:
geometry module is being loaded; __name__ = geometry
12.56636
20
...
The line printed when main.py imported the module, before anything else in main.py ran. A module should normally contain only definitions (functions, classes, constants), not code with side effects such as printing or reading input. That is where the next idea helps.
3. name and the main guard
Every module has a variable __name__:
| How the file is used | Value of __name__ inside it |
|---|---|
| imported by another file | the module's name, e.g. "geometry" |
run directly (python geometry.py) |
the special string "__main__" |
(Running main.py itself shows print(__name__) giving __main__.) So a file can tell whether it is the starting point or a helper. The standard pattern puts "run" code under a guard:
if __name__ == "__main__":
print("running geometry directly")
print(circle_area(1), rect_area(2, 3))
Run directly with python geometry.py:
geometry module is being loaded; __name__ = __main__
running geometry directly
3.14159 6
Imported from main.py, the guarded block is skipped (only the load message appears). Use the guard for:
- a demo or quick self-test of the module;
- the entry point of a program, usually a function
main()(if __name__ == "__main__": main()); - command-line behaviour (lesson 17.8).
Without the guard, importing the module would run that code every time, which is almost never wanted.
python -m
You can also run a module by name with python -m geometry. This runs it as __main__ too, but finds it the way imports do, which matters for modules inside packages (lesson 16.3).
4. Private names and documentation
A name that starts with an underscore (_check) is, by convention, private to the module: not part of its public interface. Python does not enforce it, but tools and from module import * skip such names, and readers know not to depend on them (lesson 13.4 used the same idea in classes).
"""Convert between Celsius, Fahrenheit and Kelvin."""
ABSOLUTE_ZERO_C = -273.15
def _check(celsius):
if celsius < ABSOLUTE_ZERO_C:
raise ValueError(f"{celsius} C is below absolute zero")
Good module habits:
- A docstring at the top saying what the module is for.
- Docstrings on public functions (lesson 11.8).
- Constants in
UPPER_CASEnear the top. - Private helpers with a leading underscore.
- Optionally,
__all__ = ["c_to_f", ...], a list of the names thatfrom module import *should bring in.
5. Shared state and the from-import copy
A module is loaded once and shared (lesson 16.1), so its variables are shared by every importer. That can be useful (a shared configuration) or surprising. Take cnt.py:
count = 0
def bump():
global count
count += 1
return count
and a user:
import cnt
from cnt import count
cnt.bump()
cnt.bump()
print(cnt.count, count)
2 0
cnt.count is the current value (2). The name count imported with from is a separate name bound to the value 0 at the time of the import; it does not follow later changes. When a module variable can change, access it through the module (cnt.count), or provide a function that returns it.
6. Circular imports
If module a imports b and b imports a, each needs the other while still loading. With these two files:
# a.py
print("a start")
import b
print("a end")
# b.py
print("b start")
import a
print("b end", a)
running python a.py printed:
a start
b start
a start
a end
b end <module 'a' from '.../a.py'>
a end
Notice that a ran twice: once as __main__ (the script) and once as the imported module a. Circular imports often produce confusing half-loaded modules and ImportErrors such as "cannot import name ... (most likely due to a circular import)". Fix them by:
- moving the shared code into a third module that both import;
- importing inside the function that needs the other module, instead of at the top;
- redesigning so the dependency goes one way only.
7. Name clashes with the standard library
If your folder contains a file called random.py, math.py, json.py or datetime.py, then import random in a file next to it loads yours, not the standard one (lesson 16.1). Typical symptom: AttributeError: module 'random' has no attribute 'randint'. Never name your files after standard modules. A leftover __pycache__ folder (compiled files Python creates for speed) is harmless and can be deleted at any time.
Worked example: a temperature module
temperature.py is a reusable module with a guarded self-test; report.py imports and uses it. The module checks for temperatures below absolute zero with a private helper.
temperature.py:
"""Convert between Celsius, Fahrenheit and Kelvin."""
ABSOLUTE_ZERO_C = -273.15
def _check(celsius):
if celsius < ABSOLUTE_ZERO_C:
raise ValueError(f"{celsius} C is below absolute zero")
def c_to_f(celsius):
_check(celsius)
return celsius * 9 / 5 + 32
def c_to_k(celsius):
_check(celsius)
return celsius - ABSOLUTE_ZERO_C
def f_to_c(fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
_check(celsius)
return celsius
def _self_test():
assert c_to_f(100) == 212
assert round(f_to_c(212), 6) == 100
assert round(c_to_k(0), 2) == 273.15
print("temperature: all checks passed")
if __name__ == "__main__":
_self_test()
report.py:
import temperature
from temperature import c_to_f
for c in (-40, 0, 37, 100):
print(f"{c:>4} C = {c_to_f(c):>6.1f} F = {temperature.c_to_k(c):>6.2f} K")
try:
c_to_f(-300)
except ValueError as e:
print("ValueError:", e)
print([n for n in dir(temperature) if not n.startswith("_")])
print(temperature.c_to_f.__name__, "|", temperature.__doc__)
Output of python temperature.py:
temperature: all checks passed
Output of python report.py:
-40 C = -40.0 F = 233.15 K
0 C = 32.0 F = 273.15 K
37 C = 98.6 F = 310.15 K
100 C = 212.0 F = 373.15 K
ValueError: -300 C is below absolute zero
['ABSOLUTE_ZERO_C', 'c_to_f', 'c_to_k', 'f_to_c']
c_to_f | Convert between Celsius, Fahrenheit and Kelvin.
| Idea | Where |
|---|---|
| module docstring | the first line; read back with __doc__ |
| private helper | _check and _self_test start with an underscore, so the filtered dir list leaves them out |
| the guard | python temperature.py runs the self-test; import temperature does not |
| public interface | ABSOLUTE_ZERO_C, c_to_f, c_to_k, f_to_c |
| error handling | a clear ValueError for impossible input |
The temperatures are ordinary examples (-40 is where Celsius and Fahrenheit meet).
Common mistakes
- Running code at import time (printing, input, long work) instead of defining functions.
- Forgetting the main guard, so demo code runs on import.
- Naming a file like a standard module (
random.py). - Using hyphens or spaces in module file names.
- Importing a module from another folder and getting
ModuleNotFoundError(lesson 16.4). - Expecting
from m import xto track later changes tox. - Circular imports.
- Editing a module and expecting a running program to notice.
Key takeaways
- Any
.pyfile is a module; import it by its file name from the same folder. - Importing runs the file once; keep modules to definitions.
__name__is"__main__"when run directly and the module name when imported: guard demo and entry code withif __name__ == "__main__":.- Underscore names are private by convention; add a module docstring.
- Module variables are shared;
from m import xcopies the current value. - Avoid circular imports and names that clash with the standard library.
Practice
1. What does if __name__ == "__main__": protect against?
Show answer
Running demo or start-up code when the file is merely imported by another file.
2. What is __name__ when you run python tools.py and when another file does import tools?
Show answer
"__main__" when run directly; "tools" when imported.
3. Why shouldn't you name your file json.py?
Show answer
import json could load your file instead of the standard library module, breaking code that expects the real one.
4. What does a leading underscore on a function name signal?
Show answer
That it is private to the module (an internal helper), not part of the public interface.
5. After from cnt import count, cnt.bump() changes cnt.count. Does the name count change?
Show answer
No. count still holds the value it had at import time; use cnt.count to see the current value.
6. How can you break a circular import between a and b?
Show answer
Move the shared code into a third module, import inside the function that needs it, or restructure so only one direction of dependency exists.