Python - splitting a module into multiple files


Python Clean Code Tip:

When your module becomes too big you can restructure it to a package while keeping all the imports from the module as they were.

👇

# BEFORE

# models.py
class Order:
    pass


class Shipment:
    pass


# └── models.py


# AFTER

# change to package
# models/__init__.py
from .order import Order
from .shipment import Shipment

__all__ = ["Order", "Shipment"]


# models/order.py
class Order:
    pass


# models/shipment.py
class Shipment:
    pass


# └── models
#     ├── __init__.py
#     ├── order.py
#     └── shipment.py


# imports from module/package can stay the same
from models import Order, Shipment