Modules & Imports
Overview
Organize your code by dividing it across multiple files, and import them as modules.
Learning Objectives
- Import code using import, from, and as.
- Prevent circular import dependency errors.
- Use name to create script entry points.
Concept Explanation
Every Python file is a module. Importing a module runs its code and binds its namespace. Use if __name__ == '__main__' to write code that only executes when the script is run directly, and not when it is imported into another file.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
import math
print(math.sqrt(16))
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
from datetime import datetime as dt
print(f'Current time is: {dt.now()}')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
def run_operations():
print('Running standalone calculations.')
if __name__ == '__main__':
# Executes only if run directly
run_operations()
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Trigger Import → Search sys.modules → Load code → Execute module statements → Bind namespace
Common Mistakes
Review these common pitfalls when working with this topic:
- Creating circular imports where module A imports B, and B imports A.
- Using wildcard imports (from math import *) that pollute namespaces.
- Naming local scripts the same as standard modules (e.g. naming your file 'math.py').
- Forgetting script check guards inside files that are meant to be imported as libraries.
Best Practices
Enforce these Pythonic best practices in your codebase:
from math import * # Pollutes namespace
import math # Clean namespace references
Quick Revision
Use these key summaries for last-minute revision:
- Modules are standard .py files.
- import statement exposes code tools.
- Wildcard imports make code harder to debug.
- name checks if a file is the main script.
- Python caches imports inside sys.modules.
- Avoid shadowing standard library names.