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

  1. Place import statements at the top of the file.
  2. Use absolute imports when possible.
  3. 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.
  • importlib allows 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.path at runtime is fragile; prefer installing packages properly with pip.