Python 包
结构 multi-file 项目使用包, __init__.py, 相对导入, and 命名空间包.
你将学到
- 创建包 使用 directories and __init__.py
- Use 绝对 and 相对导入
- 理解 __init__.py and 包 initialization
- 结构项目使用 subpackages
- 安装包 in development 模式
概念讲解
What Is a Package?
package 是一种 directory containing Python modules. The directory must contain an __init__.py file (which can be empty) to be recognized as a package in traditional Python:
myproject/
├── __init__.py
├── models/
│ ├── __init__.py
│ ├── user.py
│ └── product.py
├── utils/
│ ├── __init__.py
│ ├── strings.py
│ └── files.py
└── main.py
The __init__.py file marks a directory as a package. It can be empty, or it can contain initialization code that runs when the package is imported. In Python 3.3+, namespace packages work without __init__.py, but explicit packages are still recommended for clarity.
The __init__.py File
The __init__.py runs when the package is first imported. You can use it to:
# models/__init__.py
from .user import User
from .product import Product
__all__ = ["用户", "Product"]
__version__ = "1.0.0"
This lets users import directly from the package: 从 models 导入 用户 instead of 从 models.用户 导入 用户. The __init__.py acts as the package's public API.
Absolute Imports
Absolute imports use the full dotted path from the project root:
# main.py
from models.user import User
from utils.strings import capitalize
from utils.files import read_csv
Absolute imports are recommended — they are explicit, clear, and not affected by the importing module's location. PEP 8 explicitly recommends absolute imports.
Relative Imports
Relative imports use dots to navigate relative to the current module's position in the package:
# models/user.py
from . import product # same package (models)
from ..utils.strings import capitalize # parent package, then utils
from .product import Product # specific module in same package
.— current package..— parent package...— grandparent package
Relative imports are useful within a package but can only be used inside a package (not in the top-level script). They can make refactoring harder because the import meaning depends on the file's location.
Structuring a Project
A well-structured Python project:
myapp/
├── pyproject.toml # project metadata and dependencies
├── README.md
├── src/
│ └── myapp/ # the actual package
│ ├── __init__.py
│ ├── cli.py # command-line interface
│ ├── core/
│ │ ├── __init__.py
│ │ ├── calculator.py
│ │ └── parser.py
│ └── utils/
│ ├── __init__.py
│ └── helpers.py
└── tests/
├── test_calculator.py
└── test_parser.py
The src/ layout separates your package from the project root, preventing accidental imports from the working directory during testing. pyproject.toml is the modern standard for project configuration (replacing 设置.py).
Installing Your Own Package
To install your own package in development mode (changes are reflected immediately without reinstalling):
pip install -e .
This creates a link to your source code instead of copying it. You can then import your package from anywhere:
import myapp
from myapp.core.calculator import Calculator
The -e (editable) flag is essential during development — it lets you modify your code and test the changes without reinstalling after every edit.
Namespace Packages
Python 3.3+ supports namespace packages — packages split across multiple directories without __init__.py. This is used by large projects that span multiple repositories:
company/
├── billing/ # no __init__.py — namespace package
│ └── invoices.py
└── shipping/ # no __init__.py — namespace package
└── orders.py
For most projects, traditional packages with __init__.py are clearer and recommended.
示例代码
# --- Project structure ---
# myapp/
# ├── __init__.py
# ├── models/
# │ ├── __init__.py
# │ ├── user.py
# │ └── product.py
# ├── utils/
# │ ├── __init__.py
# │ └── helpers.py
# └── main.py
# --- models/__init__.py ---
# from .user import User
# from .product import Product
# __all__ = ["User", "Product"]
# --- models/user.py ---
# class User:
# def __init__(self, name, email):
# self.name = name
# self.email = email
# def __repr__(self):
# return f"User({self.name!r})"
# --- main.py using absolute imports ---
# from myapp.models import User, Product
# from myapp.utils.helpers import format_email
# --- Example of __init__.py with version ---
# myapp/__init__.py:
__version__ = "1.2.3"
__author__ = "Ada Lovelace"
# When someone does: import myapp
# They get access to: myapp.__version__, myapp.__author__
# --- Relative imports inside the package ---
# In models/user.py:
# from ..utils.helpers import validate_email # go up to myapp, then utils
# from .product import Product # same package (models)
# --- Installing in development mode ---
# $ pip install -e .
# This lets you: import myapp # from anywhere on the system
# --- Checking package metadata ---
import importlib.metadata
# In Python 3.8+:
# version = importlib.metadata.version("myapp")
# print(version) # 1.2.3
print("Package structure defines how Python code is organized")
print(f"Version: {__version__}, Author: {__author__}")
Shows 项目结构使用包 and subpackages, __init__.py 使用 re-导出 and metadata, 绝对 and 相对导入示例, editable 安装 command, and 包 metadata access.
动手试一试
- JSON Formatter
包配置 files (pyproject.toml) use structured 格式.
- 情况 Converter
包 and 模块 naming — snake_case for 模块, snake_case for 包.
常见错误
错误写法
运行 script 使用相对导入 directly as python models/用户.py
正确做法
相对导入仅 工作当 模块是 imported as 部分的 包, 不运行 directly. Use 'python -m myapp.主要' 到运行 as 模块, or restructure 到 use 绝对导入 for 条目点.
错误写法
Forgetting __init__.py and wondering 为什么导入失败
正确做法
不使用 __init__.py (in Python < 3.3), directory 是不 包 and 导入失败使用 ModuleNotFoundError. 创建空 __init__.py in 每个包 directory. Python 3.3+ 有命名空间包, 但 explicit __init__.py 是 still clearer.
相关资源
相关速查表
- Python Cheatsheet
包结构, 导入, and __init__.py 引用.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。