The import statement lets you use code that lives in another file. It’s how you load Python’s standard library (math, random, datetime), third-party packages you install with pip (requests, pandas), and your own modules, so you can split a program into small, reusable pieces.
In this tutorial, you’ll learn every form of the import statement, how Python finds and loads modules, how packages and relative imports work, and how to fix the import errors beginners run into most often.
Key terms used in this article:
- Module: A single Python file (
.py). The module name is the file name without.py. For example,helpers.pyis the modulehelpers. - Package: A folder that groups related modules. It usually contains an
__init__.pyfile. - Namespace: A mapping of names to objects. Each module has its own namespace, so names in different modules don’t clash.
- Standard library: The modules that come with Python, such as
math,os, andjson. - sys.path: The list of folders Python searches when you import a module.
Table of contents
- Why import is needed
- Form 1: import module
- Form 2: from module import name
- Form 3: aliases with as
- Form 4: from module import * (avoid it)
- Importing your own modules
- The if __name__ == “__main__” check
- How Python finds a module
- Packages
- Absolute vs. relative imports
- Importing third-party packages
- Importing dynamically with importlib
- Inspecting a module
- Organizing imports: PEP 8 best practices
- Circular imports
- Common import errors and how to fix them
- Practice exercises
- Summary
Why import is needed
Python keeps its core small. Extra tools live in modules that you load only when you need them:
Output:
9.0 3.141592653589793 120
Without import math, the name math doesn’t exist, and Python raises NameError: name 'math' is not defined.
Form 1: import module
import module_name loads the module and creates one name in your code: the module itself. You access its contents with a dot:
Output:
3 Friday
This form keeps it clear where each name comes from (random.randint, not just randint), which is why many style guides prefer it.
You can import several modules in one line (import os, sys), but PEP 8, Python’s style guide, recommends one import per line.
Form 2: from module import name
from module import name copies specific names into your namespace, so you can use them without the module prefix:
Output:
7.0 3.142 5
For long import lists, wrap the names in parentheses:
Output:
reports/2026/summary.txt notes.txt
Form 3: aliases with as
as gives an imported module or name a different local name. This is common for long names and widely used conventions:
Output:
2026
[('a', 3)]
Some aliases are universal conventions in the Python community, and you’ll see them in almost every project:
| Import | Convention |
|---|---|
import numpy as np | NumPy |
import pandas as pd | pandas |
import matplotlib.pyplot as plt | Matplotlib |
import seaborn as sns | seaborn |
import tensorflow as tf | TensorFlow |
Aliases also solve name clashes when two modules have a function with the same name, such as from json import loads as json_loads.
Form 4: from module import * (avoid it)
from module import * imports every public name from a module:
Output:
3 4.0
Avoid this outside quick experiments in the interactive shell. It hides where names come from, and it can silently overwrite your own variables or built-in functions. For example, from os import * replaces the built-in open() with os.open(), which works completely differently.
A module can control what * imports by defining a list named __all__.
Importing your own modules
Any .py file can be imported by another file in the same folder. The following example creates a module file and then imports it. Run it, and you’ll see that it works just like importing from the standard library:
Output:
Hello, Jessa! Goodbye, friend! friend Utilities for greeting people.
In a real project, you’d simply write greetings.py in your editor and save it next to your main script:
my_project/ ├── main.py └── greetings.py
Then import greetings in main.py just works. Never name your own file after a standard library module, such as random.py or math.py, because your file will be imported instead of the real module.
The if __name__ == “__main__” check
When Python imports a module, it runs all of its top-level code. Every module has a built-in variable __name__. It’s set to "__main__" when the file is run directly, and to the module’s name when it’s imported. Use this to keep test or demo code from running on import:
Output:
calc.py: __name__ is calc 30 __main__
If you ran python calc.py from the command line, both print statements inside the file would run, because __name__ would be "__main__".
How Python finds a module
When you write import something, Python:
- Checks
sys.modules, a cache of modules that are already loaded. If the module is there, it’s reused. - Searches the folders in
sys.path, in order, for a file or package namedsomething. - Runs the module’s code once, creates a module object, stores it in
sys.modules, and binds the name in your namespace.
sys.path usually contains, in this order:
- The folder of the script you ran (or the current folder in the interactive shell)
- Folders listed in the
PYTHONPATHenvironment variable - The standard library folders
- The
site-packagesfolder, where pip installs third-party packages
Output:
<class 'list'> True True
To see where a module was loaded from, check its __file__ attribute:
Output:
__init__.py json
Modules are imported only once
Because of the sys.modules cache, importing the same module again doesn’t run its code again:
Output:
counter_mod is loading... 1 True
Packages
A package is a folder of modules. Import a module from a package with a dotted name:
shop/
├── __init__.py
├── cart.py
└── payments/
├── __init__.py
└── cards.py
Output:
Initializing shop package 35 ************4444 ************0004
What __init__.py does
- It marks a folder as a regular package. Its code runs the first time the package is imported, as you saw from the printed message.
- It can be empty, which is the most common case.
- It can import names to create a simpler public interface. For example, adding
from .cart import totaltoshop/__init__.pylets users writefrom shop import total.
Since Python 3.3, a folder without __init__.py can also be imported as a namespace package, but including __init__.py is still the recommended, predictable choice for your own projects.
Absolute vs. relative imports
Inside a package, modules can import each other in two ways.
Absolute imports use the full path from the project’s top-level package:
Relative imports use dots to start from the current package. One dot means the current package, and two dots mean the parent package:
PEP 8 recommends absolute imports because they’re easier to read. Relative imports are fine for imports within a large package.
Relative imports only work inside a package. Running a module that uses them directly as a script (python shop/payments/cards.py) fails with ImportError: attempted relative import with no known parent package. Run it as a module from the project root instead: python -m shop.payments.cards.
Importing third-party packages
Packages from the Python Package Index (PyPI) must be installed before you can import them:
python -m pip install requests
The name you install isn’t always the name you import. For example, you install beautifulsoup4 but import bs4, and you install pillow but import PIL. Use a virtual environment for each project so their packages don’t conflict.
Importing dynamically with importlib
When the module name is only known at runtime, for example from a settings file or user choice, use importlib.import_module():
Output:
math -> math json -> json statistics -> statistics 5
Reloading a module
Because modules are cached, editing a module’s file doesn’t affect a running program. During interactive development, importlib.reload() re-runs the module’s code:
Output:
development production
Inspecting a module
Output:
['log', 'log10', 'log1p', 'log2'] Return the square root of x.
Use dir(module) to list a module’s names and help(module) to read its documentation.
Organizing imports: PEP 8 best practices
- Put imports at the top of the file, after the module docstring and comments.
- Use one import per line.
- Group imports in this order, with a blank line between groups: standard library imports, then third-party imports, then your own application’s imports.
- Within each group, sort the imports alphabetically.
- Prefer absolute imports, and avoid wildcard (
*) imports.
Tools such as isort and Ruff can sort imports automatically.
Circular imports
A circular import happens when module a imports module b, and module b imports module a. One of them is only partly loaded when the other tries to use it, so you get an ImportError such as cannot import name 'a_func' from partially initialized module 'module_a'. The exact wording varies between Python versions.
Output:
ImportError: cannot import name 'a_func' from 'module_a'
Ways to fix it:
- Move shared code into a third module that both can import. This is usually the best fix.
- Import the module instead of a name:
import module_band callmodule_b.b_func()inside a function, so the name is looked up later. - Move the import inside the function that needs it, as a last resort.
Common import errors and how to fix them
1. ModuleNotFoundError: No module named ‘xyz’
Output:
ModuleNotFoundError - No module named 'xyzlib_does_not_exist'
Python couldn’t find the module. Check the spelling (module names are case-sensitive), install it with python -m pip install, make sure the package is installed in the same Python or virtual environment you’re running, and check that your file is in the right folder.
2. ImportError: cannot import name ‘x’ from ‘module’
Output:
ImportError - cannot import name 'square_root' from 'math' (unknown location)
The module exists, but it doesn’t contain that name. Check the spelling and the library’s documentation, or look for a circular import. ModuleNotFoundError is a subclass of ImportError.
3. Your file shadows a real module
If you save a file named random.py and then write import random in another file in the same folder, Python imports your file. You’ll see errors such as AttributeError: module 'random' has no attribute 'randint'. Rename your file and delete any __pycache__ folder next to it.
4. AttributeError after import package
import shop doesn’t automatically import its submodules. Import the submodule explicitly, as in import shop.cart, or import it in __init__.py.
Practice exercises
Exercise 1: Import only randint and choice from random, and use them to pick a random number from 1 to 6 and a random color.
Output:
3 red
Exercise 2: Create a module converter.py with a function km_to_miles(), add a demo inside if __name__ == "__main__":, then import the function under the alias to_miles.
Output:
26.22
Exercise 3: Ask for a module name as a string and print how many public names it has, using importlib.
Output:
string has 12 public names, such as ['Formatter', 'Template', 'ascii_letters']
Summary
import moduleloads a module and gives you access throughmodule.name.from module import namebrings specific names into your namespace.asrenames a module or name.- Avoid
from module import *, because it hides where names come from and can overwrite existing names. - Python searches
sys.pathfor modules and runs each module only once, caching it insys.modules. - Use
if __name__ == "__main__":for code that should run only when a file is executed directly. - Packages are folders of modules, usually with an
__init__.py. Use absolute imports, or relative imports inside packages. - Fix
ModuleNotFoundErrorby checking the name, installing the package in the right environment, and avoiding file names that shadow real modules. Fix circular imports by moving shared code into its own module.
Also, See:

Leave a Reply