Reusable modules and project dependencies
3.15.2
Organize application code, define a script entry point, and record dependency versions.
On this page
Separate calculations from the entry point
Put calculations and data transformations in importable functions. A main() function handles workflow, messages, and inputs. The __name__ guard runs main only when the file is launched as the top-level program.
def total(values):
return sum(values)
def main():
print(total([2, 3]))
if __name__ == "__main__":
main()
Example output
5
Record the environment
Use a virtual environment per project. Record the Python version and dependencies so colleagues can reproduce the run. A requirements file can pin an application environment, and pyproject.toml can declare project metadata and dependency requirements for packaging.
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt