Modules, imports, and packages
A module is a file of Python code that other files can import.
How it works
When two reports need the same price calculation, put it in one function and import it from both reports. Import the name you need and keep shared modules focused. An import makes definitions available before your calling code runs.
Walk through an example
Keep total in prices.py, then write from prices import total in the program that needs it. Use the if __name__ == "__main__" guard for actions that should happen only when that file is run directly.
What to watch for
Top-level statements run when a module is first imported. Keep prompts and file-writing operations behind a function or entry-point guard.
Code example
def total(prices):
return sum(prices)
if __name__ == "__main__":
print(total([3, 4]))Check your understanding
What happens when another file imports total from prices?
See the example and explanation
- Worked example
- Given
prices.py defines total and has an unguarded print - Answer
The top-level print runs.
Importing the module runs its top-level code before the requested name is made available.