PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Python import Statement Explained: Modules, Packages, and Best Practices

Python import Statement Explained: Modules, Packages, and Best Practices

Updated on: December 4, 2026 | Leave a Comment

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.py is the module helpers.
  • Package: A folder that groups related modules. It usually contains an __init__.py file.
  • 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, and json.
  • 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
    • Modules are imported only once
  • Packages
    • What __init__.py does
  • Absolute vs. relative imports
  • Importing third-party packages
  • Importing dynamically with importlib
    • Reloading a module
  • 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:

import math

print(math.sqrt(81))
print(math.pi)
print(math.factorial(5))Code language: Python (python)

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:

import random
import datetime

random.seed(1)
print(random.randint(1, 10))
print(datetime.date(2026, 12, 4).strftime("%A"))Code language: Python (python)

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:

from math import sqrt, pi, ceil

print(sqrt(49))
print(round(pi, 3))
print(ceil(4.1))Code language: Python (python)

Output:

7.0
3.142
5

For long import lists, wrap the names in parentheses:

from os.path import (
    basename,
    dirname,
    join,
)

print(join("reports", "2026", "summary.txt"))
print(basename("/home/jessa/notes.txt"))Code language: Python (python)

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:

import datetime as dt
from collections import Counter as Tally

today = dt.date(2026, 12, 4)
print(today.year)
print(Tally("banana").most_common(1))Code language: Python (python)

Output:

2026
[('a', 3)]

Some aliases are universal conventions in the Python community, and you’ll see them in almost every project:

ImportConvention
import numpy as npNumPy
import pandas as pdpandas
import matplotlib.pyplot as pltMatplotlib
import seaborn as snsseaborn
import tensorflow as tfTensorFlow

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:

from math import *

print(floor(3.7), sqrt(16))Code language: Python (python)

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:

# Create a module file named greetings.py
code = '''
"""Utilities for greeting people."""

DEFAULT_NAME = "friend"

def hello(name=DEFAULT_NAME):
    return f"Hello, {name}!"

def goodbye(name=DEFAULT_NAME):
    return f"Goodbye, {name}!"
'''
with open("greetings.py", "w") as f:
    f.write(code)

# Import it like any other module
import greetings
from greetings import goodbye

print(greetings.hello("Jessa"))
print(goodbye())
print(greetings.DEFAULT_NAME)
print(greetings.__doc__)Code language: Python (python)

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:

code = '''
def area(width, height):
    return width * height

print("calc.py: __name__ is", __name__)

if __name__ == "__main__":
    print("Running calc.py directly: demo", area(3, 4))
'''
with open("calc.py", "w") as f:
    f.write(code)

import calc  # the demo inside the if block does not run

print(calc.area(5, 6))
print(__name__)Code language: Python (python)

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:

  1. Checks sys.modules, a cache of modules that are already loaded. If the module is there, it’s reused.
  2. Searches the folders in sys.path, in order, for a file or package named something.
  3. 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 PYTHONPATH environment variable
  • The standard library folders
  • The site-packages folder, where pip installs third-party packages
import sys

print(type(sys.path))
print(len(sys.path) > 0)
print(sys.modules["sys"] is sys)  # sys itself is cached in sys.modulesCode language: Python (python)

Output:

<class 'list'>
True
True

To see where a module was loaded from, check its __file__ attribute:

import json
import os

print(os.path.basename(json.__file__))
print(json.__name__)Code language: Python (python)

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:

with open("counter_mod.py", "w") as f:
    f.write('print("counter_mod is loading...")\nvalue = 0\n')

import counter_mod
import counter_mod  # no second "loading" message

counter_mod.value += 1
import counter_mod
print(counter_mod.value)  # same module object, so the change is kept

import sys
print("counter_mod" in sys.modules)Code language: Python (python)

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
import os

# Build the package structure shown above
os.makedirs("shop/payments", exist_ok=True)
files = {
    "shop/__init__.py": 'print("Initializing shop package")\n',
    "shop/cart.py": "def total(prices):\n    return sum(prices)\n",
    "shop/payments/__init__.py": "",
    "shop/payments/cards.py": "def mask(number):\n    return '*' * 12 + number[-4:]\n",
}
for path, content in files.items():
    with open(path, "w") as f:
        f.write(content)

# Different ways to import from a package
import shop.cart
from shop.payments import cards
from shop.payments.cards import mask

print(shop.cart.total([10, 20, 5]))
print(cards.mask("4111222233334444"))
print(mask("5500000000000004"))Code language: Python (python)

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 total to shop/__init__.py lets users write from 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:

# shop/payments/cards.py
from shop.cart import totalCode language: Python (python)

Relative imports use dots to start from the current package. One dot means the current package, and two dots mean the parent package:

# shop/payments/cards.py
from . import utils          # shop/payments/utils.py
from .utils import helper    # a name from shop/payments/utils.py
from ..cart import total     # shop/cart.pyCode language: Python (python)

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
import requests

response = requests.get("https://pynative.com")
print(response.status_code)Code language: Python (python)

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():

import importlib

for name in ["math", "json", "statistics"]:
    module = importlib.import_module(name)
    print(name, "->", module.__name__)

stats = importlib.import_module("statistics")
print(stats.mean([2, 4, 9]))Code language: Python (python)

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:

import importlib

with open("settings_mod.py", "w") as f:
    f.write("MODE = 'development'\n")

import settings_mod
print(settings_mod.MODE)

with open("settings_mod.py", "w") as f:
    f.write("MODE = 'production'\n")

importlib.invalidate_caches()
importlib.reload(settings_mod)
print(settings_mod.MODE)Code language: Python (python)

Output:

development
production

Inspecting a module

import math

print([name for name in dir(math) if name.startswith("log")])
print(math.sqrt.__doc__.splitlines()[0])Code language: Python (python)

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.
"""Report generator."""

# 1. Standard library
import json
import os
from datetime import date

# 2. Third-party packages
import requests

# 3. Local application
from shop.cart import totalCode language: Python (python)

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.

with open("module_a.py", "w") as f:
    f.write("from module_b import b_func\n\ndef a_func():\n    return 'A'\n")
with open("module_b.py", "w") as f:
    f.write("from module_a import a_func\n\ndef b_func():\n    return 'B'\n")

try:
    import module_a
except ImportError as error:
    print("ImportError:", str(error).split(" (")[0])Code language: Python (python)

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_b and call module_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’

try:
    import xyzlib_does_not_exist
except ModuleNotFoundError as error:
    print(type(error).__name__, "-", error)Code language: Python (python)

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’

try:
    from math import square_root
except ImportError as error:
    print(type(error).__name__, "-", error)Code language: Python (python)

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.

from random import randint, choice, seed

seed(7)
print(randint(1, 6))
print(choice(["red", "green", "blue"]))Code language: Python (python)

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.

with open("converter.py", "w") as f:
    f.write(
        "def km_to_miles(km):\n"
        "    return round(km * 0.621371, 2)\n\n"
        "if __name__ == '__main__':\n"
        "    print(km_to_miles(10))\n"
    )

from converter import km_to_miles as to_miles

print(to_miles(42.195))Code language: Python (python)

Output:

26.22

Exercise 3: Ask for a module name as a string and print how many public names it has, using importlib.

import importlib

module_name = "string"
module = importlib.import_module(module_name)
public = [n for n in dir(module) if not n.startswith("_")]
print(f"{module_name} has {len(public)} public names, such as {public[:3]}")Code language: Python (python)

Output:

string has 12 public names, such as ['Formatter', 'Template', 'ascii_letters']

Summary

  • import module loads a module and gives you access through module.name.
  • from module import name brings specific names into your namespace. as renames a module or name.
  • Avoid from module import *, because it hides where names come from and can overwrite existing names.
  • Python searches sys.path for modules and runs each module only once, caching it in sys.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 ModuleNotFoundError by 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:

  • Python Modules
  • Running Python Scripts From the Command Line
  • How to Install Python on Windows, macOS, and Linux
  • Top 20+ Python Functions and Modules Interview Questions

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com