Lesson 15 of 16 · Project Setup
Project Structure
Organise a Python project the professional way: split code into modules and packages, import your own code, use if __name__ == '__main__' and lay out your folders.
- 8 min read
- Intermediate
- Reviewed
- How to split a program into modules and import your own code
- What a package is and what __init__.py does
- What if __name__ == "__main__" is for
- A simple folder layout you can use for any project
From one file to many
Small programs fit in one file. As a project grows, one long file becomes hard to read and hard to change. The fix is to split it into several files, each with one job.
Your own modules
Any .py file is a module, and you can import it just like json or csv. Suppose you have two files in the same folder:
# greetings.py
def hello(name):
return f"Hello, {name}!"# main.py
import greetings
print(greetings.hello("Ada"))Running python main.py prints Hello, Ada!. Python found greetings.py because it is in the same folder as main.py.
You can try the same idea right here. This example first writes a small module file, then imports it.
from pathlib import Path
import importlib
Path("greetings.py").write_text(
'def hello(name):\n'
' return f"Hello, {name}!"\n'
'\n'
'LANGUAGES = ["en", "fr", "hi"]\n'
)
importlib.invalidate_caches()
import greetings
from greetings import hello, LANGUAGES
print(greetings.hello("Ada"))
print(hello("Grace"))
print(LANGUAGES)importlib.invalidate_caches() is only needed here because the file was created by the same program a moment earlier. In a real project the file already exists and you just import it.
Packages: folders of modules
When you have several related modules, put them in a folder. A folder of modules is a package. It usually contains a file called __init__.py, which marks it as a package and runs when the package is first imported. It can simply be empty.
weather/
├── __init__.py
├── api.py
└── formatting.pyImport from it with dots:
from weather.api import get_forecast
from weather.formatting import format_temperatureif __name__ == "__main__"
When Python runs a file directly, it sets the special variable __name__ to "__main__". When the file is imported by another file, __name__ is set to the module's name instead.
That lets a file behave differently in the two situations: run some code only when it is started directly, and not when someone imports its functions.
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def main():
for celsius in [0, 25, 100]:
print(f"{celsius}°C = {celsius_to_fahrenheit(celsius)}°F")
if __name__ == "__main__":
main()Run this file, and main() runs. Import it from another file with from converter import celsius_to_fahrenheit, and you get the function without the printing. This pattern, a main() function plus the if check at the bottom, appears at the end of countless Python files.
A layout for real projects
Here is a simple, common layout. You will see something like it in most Python projects on GitHub.
weather-app/
├── .venv/ not shared: your virtual environment
├── .gitignore tells Git what to leave out
├── README.md what the project does and how to run it
├── requirements.txt the packages it needs
├── main.py the starting point
├── weather/ the project's own package
│ ├── __init__.py
│ ├── api.py talking to a weather service
│ └── formatting.py turning numbers into readable text
└── tests/
└── test_formatting.pyA few principles behind it:
- One job per module.
api.pyfetches data,formatting.pyformats it. When something breaks, you know where to look. - A short starting point.
main.pymostly calls functions from the package. - Tests in their own folder, named after what they test. You will write tests in Advanced Python.
- A README that explains, in a few lines, how to install and run the project.
Common mistakes
Split a small program into a function, a main() function and the __main__ check.
# Organise this program the professional way: # 1. a function km_to_miles(km) that returns km * 0.621371 rounded to 1 decimal place # 2. a function main() that prints the line below for 5 and 42.195 km # 3. the if __name__ == "__main__": check that calls main() # Output must be exactly: # 5 km = 3.1 miles # 42.195 km = 26.2 miles
What is the value of __name__ inside a module that has been imported by another file?
Summary
- Every
.pyfile is a module that you can import. - A folder of modules with an
__init__.pyfile is a package, imported with dots. if __name__ == "__main__":runs code only when the file is started directly.- A clear layout, with a README, requirements, one job per module and a short starting point, makes any project easier to work on.
Next: writing code that others can read easily.
Finished reading? Tick it off to track your progress.