A module is a Python .py file containing valid code. It groups related functions, classes, and data so a growing program can be divided into memorable categories of behavior instead of one difficult-to-navigate script. section 2.1.1 section 2.2.3
Think of a module as a labeled workspace or a small castle wall around related code. Other code uses its public names through imports, while the module keeps its own global namespace. This separation reduces cognitive load and makes responsibilities easier to find and maintain. section 2.1.1 section 3.2.1 section 11.5.1
Use modules to make structure and dependencies clearer:
- Map a concern to a module, while staying open to changing the categories as the system becomes clearer. section 2.2.3
- Import only the names you need, or import the whole module and use its prefix when drawing on many related functions. section 2.1.2
- Avoid wildcard imports because hidden names can collide and make debugging harder. section 2.1.2
- Treat modules as a higher-level encapsulation than classes; packages group related modules into a directory structure. section 3.2.1
A sales-tax module
Put tax rules and their calculation in sales_tax.py, then import the function where it is needed: # sales_tax.py TAX_RATES_BY_STATE = {'MI': 1.06} def add_sales_tax(total, state): return total * TAX_RATES_BY_STATE[state] # receipt.py from sales_tax import add_sales_tax print(add_sales_tax(total, state)) The receipt code can use the tax behavior without placing tax rules inside the receipt logic. section 2.1.1 section 2.1.2
# receipt.py
from sales_tax import add_sales_tax #1
def print_receipt():
total = ...
state = ...
print(f'TOTAL: {total}')
print(f'AFTER TAX: {add_sales_tax(total, state)}') #2
Inspect the complete receipt example to see a module import a function from sales_tax and call it during receipt generation. section 2.1.2


































