How do I import modules and manage namespaces in Python?
· Category: Python Programming
Short answer
Use import module to bring in a whole module, from module import name to import specific attributes, and from module import name as alias to avoid naming conflicts. Python resolves imports using sys.path.
Steps
- Place
importstatements at the top of the file. - Use absolute imports when possible.
- Use aliases to resolve name collisions.
import math
from datetime import datetime as dt
from collections import defaultdict
print(math.sqrt(16))
print(dt.now())
Tips
- Avoid
from module import *because it pollutes the namespace and makes it unclear where names come from. - Use
if __name__ == "__main__":to write code that runs only when the file is executed directly. - Relative imports (e.g.,
from . import module) work inside packages. importliballows dynamic imports when the module name is determined at runtime.
# Dynamic import
import importlib
module_name = "json"
json_module = importlib.import_module(module_name)
Common issues
- Circular imports occur when two modules import each other directly or indirectly; refactor shared code into a third module.
- Shadowing built-in modules or standard library names (e.g., naming a file
json.py) causes confusing import errors. - Modifying
sys.pathat runtime is fragile; prefer installing packages properly withpip.