Modules and Packages

Published by Brayan K

Organize your code, reuse functionality, and explore Python's powerful built-in libraries.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A module is code you import

Operators and Expressions began a program with import math, and lessons since have imported copy, datetime, json, csv and more. Each of those is a module: code, usually a .py file, that import runs and hands to your program. The modules that come with Python make up its standard library, and a .py file of your own can be a module too. A package is a folder of modules.

Most import mistakes come from not knowing which names an import gives you, so that's where to start.

Each kind of import gives your program different names

An import line decides which names your program gets. There are four kinds:

import math
from math import sqrt, pi
import datetime as dt
from math import floor as round_down

print(math.sqrt(16))
print(sqrt(16), pi)
print(dt.date(2026, 1, 1))
print(round_down(3.9))

# ✅ Expected output:
# 4.0
# 4.0 3.141592653589793
# 2026-01-01
# 3

So import math doesn't give you sqrt:

import math

print(math.sqrt(16))
print(sqrt(16))

# ✅ Expected output:
# 4.0

# ✅ Expected error:
# NameError: name 'sqrt' is not defined

It works the other way round too. After from math import sqrt on its own, the name math doesn't exist, and math.sqrt(16) stops with NameError: name 'math' is not defined (from Python 3.12, followed by Did you forget to import 'math'?). And import takes only modules. A function goes after from:

import math.sqrt

# ✅ Expected error:
# ModuleNotFoundError: No module named 'math.sqrt'; 'math' is not a package

A misspelling stops the program at the import line. import maths gives ModuleNotFoundError: No module named 'maths', and from random import randInt gives ImportError: cannot import name 'randInt' from 'random', followed in brackets by where the random module is stored on your computer; from Python 3.12, Did you mean: 'randint'? comes after that. When you half-remember a name, dir() lists the names a module has:

import math

print("sqrt" in dir(math), "square_root" in dir(math))
print([name for name in dir(math) if name.startswith("is")])

# ✅ Expected output:
# True False
# ['isclose', 'isfinite', 'isinf', 'isnan', 'isqrt']

PEP 8, Python's style guide, puts imports at the top of a file, one module per line: the standard library's first, then installed packages, then your own modules.

datetime is a module and a type

Dates & Times (datetime) imported its types with from datetime import ..., and with this module the import style matters more than usual: the module and its main type are both called datetime.

import datetime
from datetime import date, timedelta

print(datetime.date(2026, 1, 1))
print(datetime.datetime(2026, 1, 1, 9, 30))
print(date(2026, 1, 1) + timedelta(days=30))

# ✅ Expected output:
# 2026-01-01
# 2026-01-01 09:30:00
# 2026-01-31

After import datetime, the name datetime is the module, and the type is datetime.datetime. Import the type by name as well, and datetime changes meaning:

import datetime
from datetime import datetime

print(datetime.date(2026, 1, 1))

# ✅ Expected error:
# TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object

The second line replaced the module with the type, so datetime.date is now one of the type's methods, which expects a datetime, not a year. Choose one style per file: import datetime and write datetime.date(...) and datetime.datetime(...), or from datetime import date, datetime and write date(...) and datetime(...). The opposite mix-up, calling datetime.now() on the module, is in Dates & Times (datetime).

from … import * can replace names you already have

pi = "apple pie"
print(pow(2, 3))

from math import *

print(pi)
print(pow(2, 3))

# ✅ Expected output:
# 8
# 3.141592653589793
# 8.0

from math import * copies every public name in math into your program, and two of them land on names that were already there: your pi, and Python's built-in pow(), which gives 8 for pow(2, 3) where math's gives 8.0. Nothing warns you. With a module you know less well, it's worse: os has an open() of its own, which wants a number where the open() from File Handling takes a mode:

from os import *

notes = open("notes.txt", "w")

# ✅ Expected error:
# TypeError: 'str' object cannot be interpreted as an integer

PEP 8 says to avoid star imports, because a reader can't tell which names the file has. Name what you import, or import the module. And a module's name is an ordinary variable, so assigning to it replaces the module:

import json

json = json.dumps({"score": 3})
print(json)
print(json.loads(json))

# ✅ Expected output:
# {"score": 3}

# ✅ Expected error:
# AttributeError: 'str' object has no attribute 'loads'

After the second line, json is the text that dumps() made, and text has no loads(). Give results names of their own, such as text = json.dumps(...).

A .py file of your own is a module, and importing it runs it once

On your computer, a module of your own is a file saved next to your program: prices.py beside main.py, and import prices at the top of main.py. This site's editor holds one file, so the examples from here on write their module files first, with write_text() from Modern File Paths with pathlib, and import them after. Each Run starts in an empty folder, so the files are written fresh every time.

from pathlib import Path

Path("prices.py").write_text('''print("Running prices.py")
VAT = 0.2

def with_vat(amount):
    return round(amount * (1 + VAT), 2)
''', encoding="utf-8")

import prices
import prices
from prices import with_vat

print(prices.VAT, with_vat(10))

# ✅ Expected output:
# Running prices.py
# 0.2 12.0

The first import prices ran prices.py from top to bottom and kept the module it made, holding everything the file defined: VAT and with_vat(). The second import and the from line found it already loaded, so the file didn't run again, and its line printed once. Python runs a module once per run of a program, however many files import it.

A name you take with from is your program's own name for the module's value, not a link to the module:

from pathlib import Path

Path("prices.py").write_text("VAT = 0.2", encoding="utf-8")

import prices
from prices import VAT

VAT = 0.25
print(prices.VAT, VAT)

# ✅ Expected output:
# 0.2 0.25

Assigning to VAT changed your program's name only. The module still has 0.2, and so does any other file that reads prices.VAT.

Code that runs only when the file is the program

Every module has a name, kept in the variable __name__. A module's is the name it was imported by, and the program you run is called "__main__":

from pathlib import Path

Path("temps.py").write_text('''def to_fahrenheit(c):
    return c * 9 / 5 + 32

print("temps.py has the name", __name__)
''', encoding="utf-8")

import temps

print("This program has the name", __name__)
print(temps.to_fahrenheit(20))

# ✅ Expected output:
# temps.py has the name temps
# This program has the name __main__
# 68.0

That's how a file can tell whether it was imported or run. Code under if __name__ == "__main__": runs only when the file is the program, so other files can import its functions without setting it off:

import runpy
from pathlib import Path

Path("temps.py").write_text('''def to_fahrenheit(c):
    return c * 9 / 5 + 32

if __name__ == "__main__":
    print("Self-test:", to_fahrenheit(100))
''', encoding="utf-8")

import temps
print(temps.to_fahrenheit(20))

runpy.run_path("temps.py", run_name="__main__")

# ✅ Expected output:
# 68.0
# Self-test: 212.0

Imported, temps.py skipped its self-test, because its name was "temps". The last line runs temps.py as a program, with run_path() from the standard library's runpy module, which is what typing python temps.py in a terminal does, as in Introduction to Python. Then its name is "__main__", and the self-test runs. The programs in Building Command-Line Tools with argparse & Typer and Testing with unittest start this way.

Spot the bug: this file never prints its report, and there's no error message.

def main():
    print("Report ready")

if __name__ == "main":
    main()

print("end of file")

# ✅ Expected output:
# end of file

Nothing is called "main": the program's name is "__main__", with two underscores on each side, so the comparison is False and main() never runs. Drop the underscores from the other side instead, as in if name == "__main__":, and Python stops with NameError: name 'name' is not defined.

A file named like a standard module hides it

When you import a module, Python searches a list of folders, sys.path, in order, and takes the first match. The first folder is the one your program is in, and the standard library's folders come after it. So a file of yours called json.py next to your program is found before the real json. In this example the file goes in a folder called project, and sys.path.insert(0, "project") puts that folder first in the list, the place your program's own folder normally has:

import sys
from pathlib import Path

project = Path("project")
project.mkdir(exist_ok=True)
(project / "json.py").write_text("# my notes about JSON", encoding="utf-8")
sys.path.insert(0, "project")

import json
print(json.dumps({"a": 1}))

# ✅ Expected error:
# AttributeError: module 'json' has no attribute 'dumps'

The error names json, not your file. To see which file was imported, look at the module's __file__, the path it was loaded from. In full it's a long path, different on every computer, so this prints only its last two parts:

import sys
from pathlib import Path

project = Path("project")
project.mkdir(exist_ok=True)
(project / "json.py").write_text("# my notes about JSON", encoding="utf-8")
sys.path.insert(0, "project")

import json
where = Path(json.__file__)
print(where.parent.name, where.name)
print("dumps" in dir(json))

# ✅ Expected output:
# project json.py
# False

The fix is to rename your file. On your computer, with json.py next to main.py, Python 3.10 to 3.12 stop with the same AttributeError as above. Python 3.13 adds a hint to it: (consider renaming '…/json.py' since it has the same name as the standard library module named 'json' and prevents importing that standard library module), with your folder's path in place of the dots.

The same thing catches a program saved as random.py that imports random and calls random.randint(): it imports itself. Python 3.10 to 3.12 say AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import), the circular import being your file importing itself; 3.13 says AttributeError: module 'random' has no attribute 'randint', with the same hint. This site's editor can't show that one: it has loaded random before your code runs, so it never looks for a random.py.

A package is a folder of modules

A package is imported with dots: shop.prices is the module prices.py in the folder shop. The folder usually holds a file called __init__.py, which can be empty. Importing the package runs its __init__.py, and nothing else:

from pathlib import Path

shop = Path("shop")
shop.mkdir(exist_ok=True)
(shop / "__init__.py").write_text("", encoding="utf-8")
(shop / "prices.py").write_text("VAT = 0.2", encoding="utf-8")

import shop
print(shop.prices.VAT)

# ✅ Expected error:
# AttributeError: module 'shop' has no attribute 'prices'

import shop didn't import prices.py. Name the module to import it: import shop.prices and then shop.prices.VAT, from shop import prices and then prices.VAT, or from shop.prices import VAT. Leave .py off: import shop.prices.py stops with ModuleNotFoundError: No module named 'shop.prices.py'; 'shop.prices' is not a package, because Python reads every dot as a step into a package.

__init__.py runs when the package is first imported, so it's where a package can import its own modules and hand out their names:

from pathlib import Path

shop = Path("shop")
shop.mkdir(exist_ok=True)
(shop / "prices.py").write_text('''VAT = 0.2

def with_vat(amount):
    return round(amount * (1 + VAT), 2)
''', encoding="utf-8")
(shop / "__init__.py").write_text("from shop.prices import with_vat", encoding="utf-8")

import shop

print(shop.with_vat(10))
print(shop.prices.VAT)

# ✅ Expected output:
# 12.0
# 0.2

Now import shop is enough for shop.with_vat(). And shop.prices works too: when __init__.py imported shop.prices, Python also stored the module on the package, under the name prices.

Is __init__.py required? Not since Python 3.3. A folder without one still imports, as a namespace package:

from pathlib import Path

kit = Path("kit")
kit.mkdir(exist_ok=True)
(kit / "tools.py").write_text('''def double(n):
    return n * 2
''', encoding="utf-8")

from kit import tools
print(tools.double(21))

# ✅ Expected output:
# 42

Namespace packages exist so that one package can be spread over several folders, which some big projects need. In your own packages, keep the __init__.py: it says the folder is meant to be a package, and it's where code like the line above goes.

Inside a package, modules can import each other with a leading dot: in a file in shop, from . import prices means prices from this same package. That works only in a module imported as part of a package; in the program you run, it stops with ImportError: attempted relative import with no known parent package. Two modules can also import each other, as long as each uses the other's names only inside functions, which run later. If one needs a name from the other while they are still being run, Python stops with an ImportError. Python 3.10 to 3.12 say the module is "partially initialized", "most likely due to a circular import". For two modules next to your program, 3.13 and 3.14 suggest renaming the file instead, "if it has the same name as a library you intended to import", without naming the cycle. Module & Package Architecture for Large Codebases covers relative imports, how to lay out a bigger project, and how to untangle circular imports.

The standard library, and packages you install

The modules that come with Python make up its standard library. From Python 3.10, sys.stdlib_module_names holds their names:

import sys

for name in ["json", "math", "csv", "requests", "bs4", "openpyxl"]:
    print(name, name in sys.stdlib_module_names)

# ✅ Expected output:
# json True
# math True
# csv True
# requests False
# bs4 False
# openpyxl False

requests, bs4 and openpyxl, from HTTP Requests & APIs, Web Scraping with BeautifulSoup and Reading CSV & Excel Files, aren't part of Python. They're third-party packages, published on PyPI, the Python Package Index, and you install them with pip, in a terminal:

python -m pip install requests

pip is a program, not Python code: typed into a .py file, pip install requests is a SyntaxError. python -m pip runs the pip that belongs to that python, so the package goes where that Python looks for it; write python3 or py in place of python if that's how you start Python. The name you install isn't always the name you import: you install beautifulsoup4 and import bs4, and install PyYAML and import yaml. Virtual Environments & Dependency Management Best Practices shows where packages go and how to give each project its own, and Packaging & Publishing Python Libraries to PyPI shows how to publish one.

This site's editor has no pip. When your code imports a package that the editor's Python (Pyodide) provides, such as bs4 or pandas, the editor loads it before the Run, and it shows a note for a package that can't run in a browser, such as requests.

These standard-library modules have lessons of their own in this course:

ModuleForLesson
refinding patterns in textRegular Expressions (re)
datetimedates, times and durationsDates & Times (datetime)
jsonJSON text to dicts and lists, and backWorking with JSON
itertoolsbuilding blocks for loopsitertools
pathlibfile and folder pathsModern File Paths with pathlib
randomrandom numbers and choicesRandomness with the random Module
statisticsaverages and spreadThe statistics Module
shutilcopying and moving files and foldersHigh-Level File Operations (shutil)

The os module: paths and folders as text

Modern File Paths with pathlib said that os.path builds the same paths as plain text. The os module is older than pathlib, and plenty of code uses it:

import os

os.makedirs("os_demo/reports", exist_ok=True)
for name in ["b.txt", "a.csv"]:
    with open(os.path.join("os_demo", name), "w", encoding="utf-8") as f:
        f.write("x")

print(sorted(os.listdir("os_demo")))
path = os.path.join("os_demo", "reports", "q1.csv")
print(os.path.basename(path))
print(os.path.dirname(path) == os.path.join("os_demo", "reports"))
print(os.path.splitext("archive.tar.gz"))
print(os.path.exists("os_demo/a.csv"), os.path.isdir("os_demo/reports"))


# ✅ Expected output:
# ['a.csv', 'b.txt', 'reports']
# q1.csv
# True
# ('archive.tar', '.gz')
# True True

os.path is one of two modules: posixpath on macOS and Linux, and ntpath on Windows. Either can be imported anywhere, to see what the other kind of computer does:

import ntpath
import posixpath

print(posixpath.join("reports", "2024", "q1.csv"))
print(ntpath.join("reports", "2024", "q1.csv"))

# ✅ Expected output:
# reports/2024/q1.csv
# reports\2024\q1.csv

os.environ, which HTTP Requests & APIs used to read an API key, is part of os too. In new code pathlib usually reads more clearly, and copying or moving whole folders is a job for the shutil module.

Practice: three imports from one package

The package is ready: shop/prices.py has VAT, with_vat() and a self-test under the __name__ check. Finish the three import lines so that the prints work. The first imports the module prices from shop, the second takes with_vat out of it, and the third gives the module the short name the last print uses. The hints at the bottom give each word.

from pathlib import Path

shop = Path("shop")
shop.mkdir(exist_ok=True)
(shop / "__init__.py").write_text("", encoding="utf-8")
(shop / "prices.py").write_text('''VAT = 0.2

def with_vat(amount):
    return round(amount * (1 + VAT), 2)

if __name__ == "__main__":
    print("Self-test:", with_vat(100))
''', encoding="utf-8")

from shop ___ prices
from shop.prices import ___
import shop.prices as ___

print(prices.with_vat(10))
print(with_vat(2.5))
print(p.VAT, p.__name__)

# 👉 replace ___ with import
# 👉 replace ___ with with_vat
# 👉 replace ___ with p

# ✅ Expected output:
# 12.0
# 3.0
# 0.2 shop.prices

The self-test doesn't print: the module was imported, not run as the program.

On your own: a weather package

Make a package called weather with a module temps.py in it, holding:

From your program, import READINGS and summary in one line, print the summary, and then run temps.py as a program with runpy.

from pathlib import Path

weather = Path("weather")
weather.mkdir(exist_ok=True)

# your code here
import runpy
from pathlib import Path

weather = Path("weather")
weather.mkdir(exist_ok=True)
(weather / "__init__.py").write_text("", encoding="utf-8")
(weather / "temps.py").write_text('''READINGS = [12.5, 18.0, 21.5, 9.0, 15.0]

def to_fahrenheit(c):
    return c * 9 / 5 + 32

def summary(readings):
    return {
        "count": len(readings),
        "mean_c": round(sum(readings) / len(readings), 1),
        "max_f": round(to_fahrenheit(max(readings)), 1),
    }

if __name__ == "__main__":
    print("Self-test:", to_fahrenheit(100))
''', encoding="utf-8")

from weather.temps import READINGS, summary

print(summary(READINGS))
runpy.run_path("weather/temps.py", run_name="__main__")

# ✅ Expected output:
# {'count': 5, 'mean_c': 15.2, 'max_f': 70.7}
# Self-test: 212.0

Practice quiz

import math, then print(math.sqrt(16)), then print(sqrt(16)). What happens?

  • 4.0, then 4.0
  • 4.0, then it stops with NameError: name 'sqrt' is not defined
  • It stops with NameError before printing anything
  • 4, then 4

Answer: 4.0, then it stops with NameError: name 'sqrt' is not defined. import math gives the program one name, math. To use sqrt on its own, import it by name: from math import sqrt.

pi = "apple pie", then from math import *, then print(pi). What prints?

  • apple pie
  • It stops with NameError
  • It stops with ImportError
  • 3.141592653589793

Answer: 3.141592653589793. The star import copies every public name in math into the program, pi included, over the names that were there.

import datetime, then from datetime import datetime, then print(datetime.date(2026, 1, 1)). What happens?

  • It stops with a TypeError, because datetime now names the type, not the module
  • 2026-01-01
  • It stops with AttributeError: module 'datetime' has no attribute 'date'
  • It stops with ImportError

Answer: It stops with a TypeError, because datetime now names the type, not the module. The second line rebinds datetime to the type, and the type's date() method expects a datetime, not a year.

prices.py starts with print("Running prices.py") and sets VAT = 0.2. A program runs import prices twice, then print(prices.VAT). What prints?

  • Running prices.py twice, then 0.2
  • 0.2
  • Running prices.py, then 0.2
  • It stops with ImportError at the second import

Answer: Running prices.py, then 0.2. The first import runs the file and keeps the module. The second finds it already loaded, so the file doesn't run again.

A file defines main(), which prints "Report ready", and ends with if __name__ == "main": main(), then print("end of file"). You run the file. What prints?

  • Report ready, then end of file
  • end of file
  • It stops with NameError
  • Report ready

Answer: end of file. The program's name is "__main__", with two underscores on each side, so the comparison with "main" is False and main() never runs.

A folder holds main.py and json.py, which holds only a comment. main.py runs import json, then print(json.dumps([1, 2])). What happens when you run main.py?

  • It stops with AttributeError: module 'json' has no attribute 'dumps'
  • [1, 2]
  • It stops with ModuleNotFoundError: No module named 'json'
  • It stops with a SyntaxError

Answer: It stops with AttributeError: module 'json' has no attribute 'dumps'. Python searches the program's own folder first, so import json finds the comment file. Python 3.13 adds a hint to the same message, suggesting you rename the file.

The folder shop has an empty __init__.py and prices.py, which sets VAT = 0.2. A program runs import shop, then print(shop.prices.VAT). What happens?

  • 0.2
  • It stops with ModuleNotFoundError: No module named 'shop.prices'
  • It stops with ImportError
  • It stops with AttributeError: module 'shop' has no attribute 'prices'

Answer: It stops with AttributeError: module 'shop' has no attribute 'prices'. Importing a package runs only its __init__.py. Import the module as well: import shop.prices, or from shop import prices.

prices.py sets VAT = 0.2. A program runs import prices, then from prices import VAT, then VAT = 0.25, then print(prices.VAT, VAT). What prints?

  • 0.25 0.25
  • 0.2 0.2
  • 0.2 0.25
  • It stops with an error

Answer: 0.2 0.25. from prices import VAT made a name in the program. Assigning to it changes that name only; the module still has 0.2.

Continue this course

Frequently asked questions

What is the __pycache__ folder next to my modules?

When Python imports one of your modules, it saves the compiled form of the module there, so that the next run can skip compiling it again. Only imported modules get one, not the program you run. It's safe to delete: Python writes it again when it needs it. This site's editor doesn't write it at all.

I changed my module, but my program still uses the old version. Why?

Python runs a module once per run of a program, so a change shows the next time the program starts, in a terminal or in this site's editor. In an interactive session (the >>> prompt), the module stays loaded until you restart the session. importlib.reload(module) runs the module again in place, but names you took with from ... import keep their old values.

Why does an import work when I start my program from one folder, and not from another?

Python looks for modules in the folder of the program you run, not in the folder your terminal is in. So python tools/report.py finds a module saved next to report.py, whichever folder you start it from, while a module that is only in the terminal's folder stops the import with ModuleNotFoundError.

Can a module's name have a dash in it, or start with a digit?

Not if you want to import it: import my-helpers is a SyntaxError, because Python reads the dash as a minus, and so is import 2024_report. Name modules the way you name variables, with lowercase letters, digits and underscores and not starting with a digit: my_helpers, report_2024.

Related lessons