Python Modules
Import code from modules, guard entry points, and pin dependencies.
Why it matters: Pinned requirements and clean imports are what make a training run reproduce on another machine.
Basics
Import a Module
Every .py file is a module. Import with import math or from math import sqrt.
Keep imports at the top of the file. Group stdlib, third-party, then your own code.
Avoid from module import *. It hides where names come from.
Tiny example
Import a stdlib module and use one function.
import math
print(math.sqrt(9))Basics
The Main Guard
if __name__ == "__main__": runs code only when you execute the file, not when you import it.
Put CLI entry points there so tests can import helpers without starting a job.
Tiny example
Run main only when the file is executed directly.
def main():
print("run entry")
if __name__ == "__main__":
main()Basics
Virtual Environments
A virtual environment gives each project its own packages.
Create one with python -m venv .venv, activate it, then install from requirements.txt.
Pin versions (pandas==2.2.3, not pandas) so rebuilds stay stable.
Tiny example
Print a pinned requirement line.
pin = "pandas==2.2.3"
print("pin:", pin)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: script entry point
Importing defines helpers. Running the file starts the demo.
In AI / ML: Preprocess and train scripts sit under if __name__ == "__main__".
example.py
Python
def preprocess(text):
return text.strip().lower()
def main():
print(preprocess(" Hello "))
if __name__ == "__main__":
main()AI / ML example 2
AI / ML: pin requirements
Exact versions, one per line.
In AI / ML: CI and Docker images lock torch, pandas, and fastapi versions.
example.py
Python
# requirements.txt shape
pins = [
"numpy==2.1.3",
"pandas==2.2.3",
"scikit-learn==1.5.2",
]
for line in pins:
print(line)Takeaways
- 1Imports go at the top, grouped by source.
- 2Guard entry points with if __name__ == "__main__".
- 3One virtual environment per project, and pin every version.