Skip to content

How Imports Work

When your Python file needs code from another file or library, you use import.

Learn Your Way

Read Build Watch Test Review Visualize
You are here Projects Videos Quiz Flashcards Diagrams

Visualize It

See how Python searches for and loads modules when you import: Open in Python Tutor

Basic import

import math
print(math.sqrt(16))    # 4.0

Import specific things

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

Import your own files

If you have two files in the same folder:

my_project/
├── main.py
└── helpers.py
# helpers.py
def greet(name):
    return f"Hello, {name}!"

# main.py
from helpers import greet
print(greet("Alice"))

Packages — folders of modules

A package is a folder that contains Python files and an __init__.py:

my_package/
├── __init__.py      # Makes this folder a package (can be empty)
├── calculator.py    # A module
└── statistics.py    # Another module
from my_package.calculator import add
from my_package import statistics

What __init__.py does

__init__.py runs when you import the package. It controls what gets exported:

# my_package/__init__.py
from my_package.calculator import add, subtract
from my_package.statistics import mean

# Now users can do:
# from my_package import add, mean

Without __init__.py, Python does not recognize the folder as a package.

The import search path

When you write import something, Python looks in this order:

  1. Current directory (the folder your script is in)
  2. Installed packages (site-packages/ — things you installed with pip)
  3. Standard library (modules that come with Python, like os, json, math)

You can see the full search path:

import sys
print(sys.path)

Common patterns

Alias (rename on import):

import pandas as pd
import numpy as np

Import everything (avoid this):

from math import *    # Bad — pollutes your namespace, hard to track what came from where

Conditional import:

try:
    import ujson as json    # Faster JSON library
except ImportError:
    import json             # Fall back to standard library

Common mistakes

Circular imports:

# file_a.py
from file_b import helper_b    # file_b imports from file_a → circular!

# file_b.py
from file_a import helper_a    # Fails with ImportError
Fix: restructure so both files import from a third file, or move imports inside functions.

Naming conflicts:

# Don't name your file "random.py" — it shadows the built-in random module!
import random    # Imports YOUR random.py instead of Python's

Missing __init__.py:

# If my_package/ has no __init__.py:
from my_package import calculator    # May fail in some Python versions

Practice

Quick check: Take the quiz

Review: Flashcard decks Practice reps: Coding challenges


← Prev Home Next →