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.
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...
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.
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).
import matplotlib.pyplot as plt
import seaborn as sns
Standard conventions (pd, np, plt, sns, tf, torch) make code instantly readable.
# 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')
sys.modules — if already loaded, return cached modulesys.path (current dir, PYTHONPATH, site-packages, stdlib)sys.modulessys.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)pip install package → site-packagessite-packages
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']
| Problem | Cause | Fix |
|---|---|---|
ModuleNotFoundError | Not installed / wrong env / typo | pip install, check venv, check spelling |
ImportError: cannot import name | Circular import / name not in module | Restructure, move imports inside functions |
| Name clash | from x import * or local file shadows stdlib | Don't name files math.py, random.py; use explicit imports |
| Relative import error | Running module as script | Run as python -m package.module or use absolute imports |