🎓 A1Learner
🔍

Python Packages

A package is a folder that holds modules. An import uses dots to name a module inside a package.

A package is a folder

The shapes folder holds one module. The empty file marks it as a package.

# shapes/__init__.py
# (this file can be empty)

# shapes/area.py
def square(side):
    return side * side

Import with a dot

The dot path leads into the folder. Then a second dot reaches the function.

import shapes.area

print(shapes.area.square(5))

Bring a function in directly

You can also import one function. Then you use its name on its own.

from shapes.area import square

print(square(3))

Example

# shapes/__init__.py
# (empty file)

# shapes/area.py
def square(side):
    return side * side

def rectangle(width, height):
    return width * height

# main.py
import shapes.area

print(shapes.area.square(4))
print(shapes.area.rectangle(3, 5))

Key points

  • Package: a folder that holds modules
  • Use dots to name a module inside a package
  • An import like shapes.area means the area module in shapes
  • __init__.py: the classic file that marks a folder as a package

In this example, the shapes folder is a package. Its area module holds two functions. The main.py file sits outside the shapes folder. It sits next to the folder, not inside it. It imports shapes.area with a dot path. Then it prints the area of a square and a rectangle.

Note

Modern Python can also use a folder without __init__.py.

Those folders are called namespace packages.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What is a package in Python?