#post
python-module-split-into-multiple-files
Tips and Tricks - Python - splitting a module into multiple files | TestDriven.io
- Refactor from a module (one file) to a package (a folder with multiple files, including
__init__.py
) - Can keep all imports from the module unchanged by rexporting the imports from
package/__init__.py
:
❗ Dramatically change this to avoid plagiarism! What did I learn in particular that adds extra value?
Before (single file module):
# models.py
class Order:
pass
class Shipment:
pass
After (multi-file package folder):
# models/__init__.py
from .order import Order
from .shipment import Shipment
__all__ = ["Order", "Shipment"]
# or...
from . import order
from . import shipment
__all__ = ["order", "shipment"]
# though, that would change the imports to order.Order and shipment.Shipment...
# models/order.py
class Order:
pass
# models/shipment.py
class Shipment:
pass
# └── models
# ├── __init__.py
# ├── order.py
# └── shipment.py
Imports from the new package are the same as they were from the previous module:
from models import Order, Shipment