Learning

Python Import System

Python Import System

import Statement

python
import math print(math.pi) # Must use module prefix # Import specific items from math import sqrt, pi print(sqrt(16)) # Used directly, no prefix # Import everything (⚠️ BAD PRACTICE — pollutes namespace) # from math import *

Aliases (as keyword)

python
from datetime import datetime as dt from collections import defaultdict as dd

Module Search Path (sys.path)

Python finds modules in this order:

  1. Current directory (or script's directory)
  2. PYTHONPATH environment variable directories
  3. Standard library directories
  4. Third-party site-packages
python
print(sys.path) # Add custom directory temporarily sys.path.append('/my/custom/modules')

The name == 'main' Guard

python
def main(): print('Running as script') # This runs ONLY when executed directly: python my_module.py # It does NOT run when imported: import my_module if __name__ == '__main__': main()

Why? Prevents test code/execution code from running when the file is imported as a module elsewhere.

Module Caching

python
import my_module # Loads and executes import my_module # Uses cached version, does NOT re-execute # Force reload (useful in Jupyter notebooks) import importlib importlib.reload(my_module) # Check what's loaded print(sys.modules.keys())

Circular Imports

python
# b.py imports a.py # ❌ This causes an error! # Solutions: # 1. Restructure code to remove circular dependency # 2. Import inside the function, not at the top of the file # def func(): # from module_b import something # Lazy import

Relative vs Absolute Imports

python
# from . import sibling_module # Relative (same directory) # from .subpkg import module # Relative (sub-directory) # from mypackage.subpkg import mod # Absolute (from project root)
Key Rules
  • •Avoid 'from module import *' — it pollutes your namespace and makes it unclear where functions come from
  • •Always use the if __name__ == '__main__': guard for script execution code
  • •Modules are cached in sys.modules after first import — use importlib.reload() if you need to re-execute
  • •Current directory is the FIRST place Python looks — never name your files the same as stdlib modules (e.g., math.py)
  • •Use aliases (as) for long module names to improve readability (e.g., import pandas as pd)
Your Task

Create a mock module structure using strings to demonstrate the concept. Write a string representing `calc.py` containing `add(a, b)` and a `if __name__ == '__main__':` block. Write another string representing `main.py` that imports from calc. Print both. Then, write a function `get_module_info(module_name)` that tries to import a given module name dynamically using `importlib.import_module` and returns its file path or 'Not found'.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should import importlib
Should show __name__ guard in string
Should define get_module_info function
Should use importlib.import_module
Should handle ModuleNotFoundError
Should access __file__ attribute