Modules and imports
If you're coming from another language
Every language has some way to pull in code from elsewhere — Java’s
import, C/C++’s #include, JS’s import/export. Python’s version: any
.py file is automatically a module, importable by its filename
(without the .py), no explicit “export” keyword needed — everything at
the top level of a file is available to whatever imports it.
This course’s sandbox supports multiple files, so the examples below run for real, across separate file tabs — showing exactly how you’d structure a small multi-file project, the same way you will in the downloadable local projects later in the course.
Importing built-in modules
Python ships with a large standard library — modules you can import without installing anything:
Two other import styles you’ll see constantly:
You’ve likely already seen this aliasing convention elsewhere
(import numpy as np, import pandas as pd); it’s the same mechanism.
Creating and importing your own module
Two files, shown as separate tabs in the sandbox — this actually runs:
No explicit “export” step — search and calculate are importable simply
because they’re defined at the top level of tools.py. This is a real
difference from JS, where you need explicit export statements, or Java,
where visibility modifiers (public, private) control what’s accessible.
if __name__ == "__main__":
Every Python file has a built-in variable __name__. When a file is run
directly (python3 main.py), __name__ is set to "__main__". When that
same file is imported by another file instead, __name__ is set to the
module’s own name (e.g. "tools") — not "__main__".
This lets you write code that only runs when the file is executed directly, not when it’s imported. Extending the same two files:
Running main.py directly does not trigger tools.py’s
if __name__ == "__main__": block — only the search function definition
gets imported, not that guarded print line. If you switched which file
you ran directly (running tools.py instead of main.py), the guarded
line would fire, printing "searching for test run". This is Python’s
rough equivalent of Java’s public static void main or C’s int main() —
a designated entry point — except every file can have one, and it’s
conditional rather than a fixed required function name.
What makes a function in a .py file importable elsewhere in Python?
Unpack both points into x, y pairs, and use math.sqrt to compute the distance between them.
Implement register in tool_registry.py, then import it into main.py and use it to build the registry, printing the final result.