A Python module supplies a namespace, and importing it can execute its top-level statements before the caller uses its functions.
Python modules: separate import-time definitions from program execution
Operation contract
The program defines a receipt-label function and guards the printing entrypoint with __name__ == "__main__". A caller importing that source can reuse the function without printing a receipt immediately. Importing a module still executes its definitions and other unguarded top-level work; the guard does not make every import side-effect free.
Failure and ownership boundary
A local file named json.py or logging.py can shadow an intended module on the search path. Put reusable code in an owned package and keep environment-dependent network or database setup out of import-time code. Python interpreter and virtual environments: run the intended executable and Python receipt CLI project: parse options and report failed input make that execution boundary explicit.
Working program
def receipt_label(identifier):
if identifier <= 0:
raise ValueError("positive identifier required")
return f"receipt:{identifier}"
if __name__ == "__main__":
print(receipt_label(41))Output
receipt:41Costs and limits
The small function allocates one label string. Import cost includes module initialization and transitive imports, which this single-file fixture does not benchmark.
Common Mistakes
- A main guard does not erase unguarded import work.
- Do not shadow library module names with local files.
Connected lessons
Python interpreter and virtual environments: run the intended executable, Python receipt CLI project: parse options and report failed input, Java modules: readability, exports and reflection boundaries.
Apply this boundary
Python package layout: owned imports and module entrypoints, Python process pools: importable workers and serialization costs.
Check the next state boundary
Python import failures: module removal does not roll back every side effect, Python plugin project: load owned code and publish only an accepted interface.
Check this related boundary
Python module cache: repeated imports reuse an owned module object.
