Creating Your Own Package
From one file to many
As a project grows, split it into modules, then group related modules into a package: a folder, usually with an __init__.py file.
myapp/
├── main.py
└── shop/
├── __init__.py # marks "shop" as a package (can be empty)
├── cart.py
└── pricing.py
Importing inside a project
- From
main.py:from shop.cart import Cart - Inside the package, a relative import:
from .pricing import apply_tax
What goes in __init__.py
It runs when the package is first imported. Use it to expose a clean public API:
from .cart import Cart
__all__ = ["Cart"]
Then users can write from shop import Cart.
Tips
- Name modules in lowercase without spaces:
user_service.py. - Don't name your file after a library (
random.py,json.py), or it will hide the real one. - Avoid circular imports (A imports B, which imports A); move shared code into a third module.
💻 Needs several files, so try it on a computer.
Example
# shop/pricing.py
TAX_RATE = 0.13
def apply_tax(amount):
return round(amount * (1 + TAX_RATE), 2)
# shop/cart.py
from .pricing import apply_tax
class Cart:
def __init__(self):
self.items = []
def add(self, name, price):
self.items.append((name, price))
def total(self):
return apply_tax(sum(price for _, price in self.items))
# shop/__init__.py
from .cart import Cart
__all__ = ["Cart"]
# main.py
from shop import Cart
cart = Cart()
cart.add("Book", 500)
cart.add("Pen", 50)
print(cart.total()) # 621.5