Python's `import` Statement: Modules, Namespaces & Best Practices

In Python, import is how you bring code from one module into another. It's not "main import" — that's not a Python term. Here's how it actually works, with the patterns you'll use daily.

Basic Import Syntax

import module_name

This loads module_name and binds it to a variable in your current namespace. You access its contents with dot notation:


import math
math.sqrt(16)  # 4.0
math.pi        # 3.14159...

Common Import Patterns

1. Import Module (Recommended Default)


import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1,2,3]})
arr = np.array([1,2,3])

Pros: Explicit, readable, avoids name clashes, shows origin.

2. Import Specific Names


from math import sqrt, pi
sqrt(16)  # 4.0 — no prefix needed
pi        # 3.14159...

Use when: You use a few names heavily. Avoid: from module import * (namespace pollution).

3. Import with Alias


import matplotlib.pyplot as plt
import seaborn as sns

Standard conventions (pd, np, plt, sns, tf, torch) make code instantly readable.

4. Conditional / Lazy Imports


# Only import heavy deps when needed
def analyze_data():
    import pandas as pd  # Local import — faster startup if unused
    return pd.read_csv('data.csv')

How Import Works Under the Hood

  1. Check sys.modules — if already loaded, return cached module
  2. Find module via sys.path (current dir, PYTHONPATH, site-packages, stdlib)
  3. Execute module code — runs top-level statements (def, class, assignments)
  4. Create module object — namespace for module's globals
  5. Cache in sys.modules
  6. Bind name in importer's namespace (per import statement)

Module Search Path (sys.path)


import sys
sys.path
# ['', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload',
#  '/home/user/.local/lib/python3.11/site-packages', ...]
  • '' = current script's directory (or CWD if interactive)
  • Install packages: pip install package → site-packages
  • Virtual environments isolate site-packages

Packages & Submodules


import package.submodule
from package import submodule
from package.submodule import function

Directory with __init__.py = package. __init__.py can expose submodules:


# package/__init__.py
from .submodule import public_function
__all__ = ['public_function']

Common Pitfalls & Solutions

Best Practices

  1. Standard library first, then third-party, then local — each group alphabetized
  2. One import per line (PEP 8)
  3. Use import module over from module import *
  4. Aliases: Use community standards (pd, np, plt, tf, torch)
  5. Avoid runtime path manipulation — use proper packaging (pyproject.toml, pip install -e .)
  6. Type checking: from __future__ import annotations + TYPE_CHECKING guards

Example: Clean Import Block


# Standard library
import json
import os
from pathlib import Path
from typing import List, Optional

# Third-party
import numpy as np
import pandas as pd
import requests

# Local
from myproject.config import settings
from myproject.models import User
from myproject.utils import logger

Python's import system is powerful, explicit, and predictable — once you understand the namespace model. The golden rule: make it obvious where every name comes from. Your future self (and teammates) will thank you.

Copyright Wanderlust World © https://www.ynyoo.com
ProblemCauseFix
ModuleNotFoundErrorNot installed / wrong env / typopip install, check venv, check spelling
ImportError: cannot import nameCircular import / name not in moduleRestructure, move imports inside functions
Name clashfrom x import * or local file shadows stdlibDon't name files math.py, random.py; use explicit imports
Relative import errorRunning module as scriptRun as python -m package.module or use absolute imports