Splitting a Program Into Pieces
A single file works exactly until it does not, somewhere around the point it holds three unrelated things. Split one program across two files, import one from the other, and watch the boundary hold.
A single file works exactly until it does not, somewhere around the point it holds three unrelated things. Split one program across two files, import one from the other, and watch the boundary hold.
One file becomes two, on purpose
Any .py file can be imported by another. Put the shared logic in its own file, and every other file that needs it imports it by name — the file name becomes the module name, minus the .py.
def area_of_circle(radius): return 3.14159 * radius * radiusimport shapes print(shapes.area_of_circle(4))What import actually does the first time
The first time a module is imported anywhere in a running program, Python actually runs the entire file top to bottom, once, then keeps the result cached. Every later import shapes, anywhere else in the program, reuses that same cached result rather than running the file again.
A package is a folder with one extra file in it
A package is just a folder of modules, with one marker file, __init__.py, that tells Python to treat the folder as a single importable unit rather than an ordinary directory.
$ geometry/ __init__.py shapes.py angles.pyFrom outside the folder, from geometry import shapes reaches into it the same way import shapes reached into a single file — the folder structure is invisible to the code that uses it.
Key takeaways
- Any .py file can be imported by another; the file name becomes the module name.
- A module's file runs top to bottom exactly once per program, the first time it is imported, then the result is cached.
- Keep a module's top level to definitions — anything meant to run belongs inside a function.
- A package is a folder with an __init__.py file, letting a folder of modules be imported as one unit.