Use an import statement to reuse definitions from another Python module instead of repeating code. Modules can hold data structures, functions, and classes, improving maintainability and reducing cognitive load. section 8.0
Choose the form that gives the current program the names it needs:
- import os binds the module name os; use names through os, such as os.path. section 8.0
- import mymod as mm and import numpy as np bind shorter aliases for modules. section 8.0
- from os import sep binds only sep, while from os import sep, path binds both selected names. section 8.0
- Avoid from os import * when explicit names make dependencies clearer. section 8.0
Split a tax calculation across two files
Put the reusable function in freedonia.py: def calculate_tax(amount, province, hour): ... Then load it in use_freedonia.py: from freedonia import calculate_tax print(calculate_tax(500, 'Harpo', 12)) The first file owns the calculation; the second imports and calls it. This keeps the implementation in one place while allowing multiple programs to reuse it. section 8.1
Loading a module executes its file from beginning to end. Python searches directories listed in sys.path, loads a module once, and records the loaded module object in sys.modules; later imports reuse it while defining the requested name. Guard executable code with if __name__ == '__main__': when it should run directly but not during import. section 8.5 section 8.7
Table 8.1 What you need to know (view table figure)
| Re-imports an already loaded module, typically to update definitions during development |
|||
Compare import forms with related module tools, including from X import Y, importlib.reload, pip, and Decimal. section 8.0












