Python Modules Introduction
In this page:
What is a Module?
A module is simply a .py file containing functions, classes, or variables -- once you 'import mymodule', everything defined at that file's top level becomes accessible as mymodule.something, which is how Python breaks large programs into organized, reusable files.
Example: What is a Module?
import math
print(math.sqrt(16))
The name Variable
Python sets every module's __name__ to __main__ only when that file is executed directly (python script.py), but to the file's own name when it's imported elsewhere -- this distinction is what the common 'if __name__ == "__main__":' guard relies on.
Example: The name Variable
print(__name__)
if __name__ == "__main__":
print("Running directly")
Mocking Modules in Memory
types.ModuleType lets you construct a module object in memory without a corresponding .py file on disk, which is a niche but genuine technique used in testing frameworks that need to fake an import without touching the filesystem.
Example: Mocking Modules in Memory
import types
fake_module = types.ModuleType("fake_module")
fake_module.greet = lambda: print("Hi from fake module")
fake_module.greet()
Active Modules Directory
Every module Python has already imported during a run is cached in the sys.modules dictionary (so re-importing the same module doesn't re-execute its code), while sys.path is the list of directories Python searches when resolving a new import.
Example: Active Modules Directory
import sys
import math
print("math" in sys.modules)
print(len(sys.path) > 0)
Reloading Modules
importlib.reload(module) re-runs a module's code and updates its namespace in place, which is occasionally useful in a long-running REPL session after editing a file -- though existing references to old objects from before the reload won't automatically update.
Example: Reloading Modules
import importlib
import math
importlib.reload(math)
print(math.pi)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: