Sub topic 1
Python Modules, Packages, and Imports
Prerequisites
You should know basic Python syntax, how to define functions, and how to run a Python file from a terminal. You should also be comfortable with files and directories.
What a Module Is
A module is a Python file that contains definitions and executable statements. A file named billing.py can define functions, classes, and constants for other code to use.
When Python loads that file, it creates a module object. The file is the source on disk. The module object is the in-memory object containing the file's namespace, including names such as billing.total.
Namespaces and Name Binding
A namespace is a mapping from names to objects. Each module has its own namespace, so a name in billing.py does not automatically conflict with a name in reports.py.
An import statement binds names in the importing module's namespace:
import math
from math import sqrt
import os.path as osp
print(math.pi)
print(sqrt(16))
print(osp.basename("/tmp/report.txt"))import math binds math. The from form binds sqrt directly. The as form binds the imported object to an alias, osp.
What Happens When You Import
Python first checks sys.modules, a dictionary that caches modules already loaded in the current process. If the module is absent, Python finds it, creates its module object, executes its top-level code, and stores the result in sys.modules.
A later import usually reuses that object instead of executing the file again. This means imports can have state and import-time side effects.
flowchart TD
A[import statement] --> B{Name in sys.modules?}
B -->|yes| C[Reuse module object]
B -->|no| D[Find and load file]
D --> E[Execute top-level code]
E --> F[Cache in sys.modules]
F --> Ccaption: Import lookup and caching alt: A flowchart showing Python reusing a cached module or finding, executing, and caching a new one.
Scripts Versus Modules
Python sets __name__ to "__main__" for the file started directly. When another file imports it, __name__ is the module's import name instead.
Use the main guard to separate reusable definitions from command-line behavior:
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("world"))The print runs when this file is executed directly, but not when another module imports greet.
Exercise
What name does import math as m bind in the current namespace?
Show answer
It binds the module object to the name m.