A package is a directory containing an __init__.py file. It allows you to group related modules together.
my_project/
├── main.py
└── ecommerce/ # The PACKAGE
├── __init__.py # Makes 'ecommerce' a package
├── products.py
├── cart.py
└── utils/
├── __init__.py # Makes 'utils' a SUBPACKAGE
└── formatting.py
# This runs when the package is imported
print('E-commerce package loaded!')
# Define package-level variables
VERSION = '2.0'
# Control what gets imported with 'from ecommerce import *'
__all__ = ['products', 'cart']
# Provide convenient imports at the package level
from .products import get_product
from .cart import ShoppingCartNow users can do:
undefinedimport ecommerce.products
ecommerce.products.get_product(1)
# Import specific item from module
from ecommerce.products import get_product
get_product(1)
# Import from subpackage
from ecommerce.utils.formatting import format_currency
# Relative imports (INSIDE the package only)
# In ecommerce/cart.py:
from .products import get_product # Same package
from ..core import database # Parent packageYou CAN have packages without __init__.py (called namespace packages). Useful for splitting a large package across multiple directories.
# Both directories contribute to 'shared_pkg'
/site-packages/shared_pkg/module_a.py
/another_path/shared_pkg/module_b.pyRecommendation: Always use __init__.py for your own projects. Namespace packages are mainly for library vendors.
def __getattr__(name):
if name == 'heavy_module':
from . import heavy_module
return heavy_module
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
# Pattern 2: Submodule import shortcut
# __init__.py
from .database import db
from .models import User, Product
# Now: from myapp import db, UserSimulate a package structure using dictionaries and strings. Create a dict `package_structure` representing an `ecommerce` package with `__init__` code, `products.py` code, and `cart.py` code. Write the `__init__.py` string so that it imports `get_product` from `products` and `ShoppingCart` from `cart` using relative imports. Print the structure clearly.