~/learn/Python · Classes & structure
Modules and structure
Split a growing script into importable pieces.
why this matters
A single 2,000-line file is unmaintainable. Splitting it into modules is what turns a script into a project.
Every .py file is a module. import brings in a whole module, from ... import pulls specific names, and as renames them.
As a script grows, separate the layers: loading data, transforming it, and reporting. Each becomes a module with small functions, which makes the pieces testable in isolation.
The `if __name__ == "__main__":` guard lets a file be both an importable module and a runnable script — the code under it only runs on direct execution.
Note
Keep import-time side effects out of modules. Importing a file should define things, not go and read a database.
Pro tip
Put code you only want to run when the file is executed directly under `if __name__ == "__main__":` so importing it stays side-effect free.
Common gotcha
Two modules importing each other causes a circular import error. Move the shared piece into a third module.
key takeaways
- A module is just a .py file you can import.
- Import only what you need from it.
- __main__ guards script-only code.
check your understanding
Why use `if __name__ == "__main__":`?
free practice
Build confidence with a question you can solve without Pro.