I. What Is a Python Package
A Python package is a mechanism for organizing modules, used to combine multiple related modules into a hierarchical code structure.
When a project has only a few features, a single .py file can be used to organize the code. But as the project grows in scale and the number of modules increases, packages become necessary to manage the relationships between modules.
1. The Difference Between Modules and Packages
Modules and packages are both code organization units in Python, but they serve different purposes.
| Aspect | Module | Package |
|---|---|---|
| Main role | Organize a set of related code | Organize multiple modules |
| Common form | .py file |
Package directory or namespace package |
| Namespace | The module's own namespace | The package's hierarchical namespace |
| Organizational capability | Single-level code organization | Multi-level code organization |
| Import style | import module |
import package.module |
For example:
my_project/
├── main.py
└── app/
├── __init__.py
├── models.py
├── services.py
└── utils.py
Where:
appis a package.models.pyis a module.services.pyis a module.utils.pyis a module.__init__.pyis the package initialization file.
It can be imported in the following ways:
import app.models
import app.services
Alternatively:
from app import models
from app import services
2. Why Packages Are Needed
Packages primarily solve the problem of code organization in large projects.
Separation of responsibilities
Place different business domains into different packages, avoiding having all code concentrated in a single directory or file.
Namespace isolation
Different packages can contain modules with the same name, distinguished by their full package paths.
Dependency management
Express the organizational relationships and dependency boundaries between modules through the package hierarchy.
Code reuse
Encapsulate common functionality as packages for use across multiple projects.
Team collaboration
Different developers can be responsible for different packages, reducing code conflicts during multi-person collaboration.
II. Structure of a Regular Python Package
The most common type of package in Python is the regular package.
Traditional regular packages are usually identified by an __init__.py file.
1. Creating a Regular Package
For example, create the following directory:
my_project/
├── main.py
└── geometry/
├── __init__.py
├── circle.py
└── rectangle.py
Here, geometry is the package, containing two modules:
circle.py: handles circle-related calculations.rectangle.py: handles rectangle-related calculations.
circle.py:
PI = 3.1415926
def area(radius):
return PI * radius ** 2
def circumference(radius):
return 2 * PI * radius
rectangle.py:
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
2. Importing Modules from a Package
You can use the full module path:
import geometry.circle
import geometry.rectangle
print(geometry.circle.area(5))
print(geometry.rectangle.area(4, 6))
You can also use:
from geometry import circle
from geometry import rectangle
print(circle.area(5))
print(rectangle.area(4, 6))
You can also import members directly from a module:
from geometry.circle import area
print(area(5))
Different styles bind different names in the current namespace; you should choose based on code size and readability.
3. Package Hierarchy
Packages can contain subpackages, forming a multi-level structure.
For example:
my_project/
├── main.py
└── application/
├── __init__.py
├── users/
│ ├── __init__.py
│ ├── models.py
│ └── services.py
├── orders/
│ ├── __init__.py
│ ├── models.py
│ └── services.py
└── common/
├── __init__.py
├── database.py
└── logger.py
Where:
applicationis the top-level package.users,orders, andcommonare subpackages.models.py,services.py,database.py, and so on are modules.
Dot notation can be used to express the hierarchical relationship:
import application.users.models
import application.orders.services
The full import name of a module is also called the Fully Qualified Module Name.
For example:
application.users.models
It clearly indicates the module's position within the overall package structure.
III. The init.py Package Initialization File
__init__.py is an important part of a traditional regular package. It identifies the package and executes the corresponding code when the package is initialized.
1. The Basic Role of init.py
In a traditional regular package, __init__.py can be an empty file:
geometry/
├── __init__.py
├── circle.py
└── rectangle.py
Even if no code is written in it, it still serves to identify the package as a regular package.
Import:
import geometry
Python will load and execute geometry/__init__.py.
Therefore, __init__.py is not merely a marker file — it is itself part of the package initialization process.
2. Defining Package-Level Attributes in init.py
You can define package-level variables in it:
# geometry/__init__.py
VERSION = "1.0.0"
AUTHOR = "Python Team"
They can be accessed directly from outside:
import geometry
print(geometry.VERSION)
print(geometry.AUTHOR)
These variables belong to the namespace of the package object.
3. Exporting a Public Interface in init.py
Suppose the project structure is:
geometry/
├── __init__.py
├── circle.py
└── rectangle.py
In circle.py:
def area(radius):
return 3.1415926 * radius ** 2
In rectangle.py:
def area(width, height):
return width * height
You can import them all in one place in __init__.py:
# geometry/__init__.py
from .circle import area as circle_area
from .rectangle import area as rectangle_area
__all__ = ["circle_area", "rectangle_area"]
Then you can use them from outside:
from geometry import circle_area, rectangle_area
print(circle_area(5))
print(rectangle_area(4, 6))
This way, the internal module structure can be hidden behind the package's public interface.
4. The Role of all
__all__ is a list of strings that specifies the names a module or package exposes when imported with a star import.
For example:
# geometry/__init__.py
from .circle import area
from .rectangle import perimeter
__all__ = ["area", "perimeter"]
Executing:
from geometry import *
Imports are performed according to the names specified by __all__.
Note the following:
__all__does not automatically import the modules or members listed in it.- It mainly controls the export behavior of
from module import *. - It does not prevent external code from explicitly importing other accessible members.
- It is not an access control mechanism, nor can it truly hide objects internal to a module.
5. init.py should not take on too many responsibilities
A common mistake is to concentrate a large amount of business logic in __init__.py.
For example:
# Not recommended
connect_database()
load_all_models()
initialize_services()
start_background_tasks()
Because when a package is imported, this top-level code may execute.
A more reasonable approach is:
- Expose only stable public interfaces.
- Define necessary package-level constants.
- Perform lightweight initialization.
- Place complex initialization logic in separate functions.
- Avoid introducing unnecessary module dependencies.
Importing a package should not implicitly start the entire application.
IV. Basic Concepts of Python Namespaces
A namespace is the mechanism by which Python manages the mapping between names and objects.
Variable names, function names, class names, and so on in Python are essentially names. A name must be bound to a specific object before it can be used in a program.
1. Relationship Between Names and Objects
For example:
name = "Python"
This statement creates a name binding:
name is bound to the string object "Python"
Here, three concepts need to be distinguished:
- Name: an identifier used in a program to refer to an object.
- Object: a data entity that actually exists at runtime.
- Namespace: a structure that stores the mapping between names and objects.
Multiple names can be bound to the same object:
a = [1, 2, 3]
b = a
print(a is b)
Output:
True
Here, a and b are two names, but they refer to the same list object.
2. The Essence of Namespaces
Conceptually, a namespace can be understood as a mapping table:
| Name | Object |
|---|---|
name |
string object |
age |
integer object |
add |
function object |
User |
class object |
Python can store the same name in different namespaces.
For example:
# module_a.py
value = "A"
# module_b.py
value = "B"
Both modules have value, but they belong to different module namespaces.
To access them:
import module_a
import module_b
print(module_a.value)
print(module_b.value)
Output:
A
B
Therefore, modules and packages not only organize code but also provide name isolation.
V. Main Types of Namespaces in Python
During program execution, Python creates multiple namespaces, and different namespaces have different scopes and lifetimes.
1. Built-in Namespace
The built-in namespace (Built-in Namespace) stores the built-in names provided by the Python interpreter.
For example:
print(len("Python"))
print(sum([1, 2, 3]))
print(type(100))
Among them:
printlensumtypeintstrlistdict
All of these are built-in names.
You can inspect them through the builtins module:
import builtins
print(builtins.len)
print(builtins.sum)
print(builtins.print)
The built-in namespace is usually created when the interpreter starts and persists while the interpreter is running.
2. Global Namespace
The global namespace usually refers to the module-level namespace.
For example:
# example.py
name = "Python"
def greet():
print(name)
Here, both name and greet belong to the module's global namespace.
You can use:
print(globals())
to view the global namespace dictionary of the current module.
In a module, globals() returns the global namespace mapping of the current module.
3. Local Namespace
A local namespace is usually created when a function is called, and it is used to store local names inside the function.
For example:
def calculate():
x = 10
y = 20
result = x + y
return result
During function execution:
xis a local name.yis a local name.resultis a local name.
After the function call ends, the local names no longer belong to the active local scope of that function call.
However, if the objects among them are still held by other references, the objects themselves will not be immediately destroyed just because the function returned.
You can use locals() to view the local namespace at the current execution point:
def calculate():
x = 10
y = 20
print(locals())
calculate()
Note that in optimized function local scopes, the mapping returned by locals() should not be treated as a reliable interface for modifying local variables.
4. Class Namespace
When a class definition is executed, a class namespace is created to store the names defined in the class body.
For example:
class User:
category = "member"
def greet(self):
return "Hello"
Here:
categorygreet
are first defined in the class namespace.
You can use:
print(User.__dict__)
to view the namespace mapping of the class.
Note that the class namespace and the instance namespace are not the same.
For example:
user = User()
user.name = "Alice"
print(User.__dict__)
print(user.__dict__)
name is bound to the instance, rather than being defined directly in the class namespace.
VI. LEGB Name Lookup Rules
Python uses the LEGB rule to describe the order in which names are looked up in function scopes.
LEGB stands for:
- L: Local, local scope.
- E: Enclosing, enclosing function scope.
- G: Global, global scope.
- B: Built-in, built-in scope.
1. LEGB Lookup Order
When a name is used inside a function, Python looks up that name according to the corresponding scope rules.
flowchart TD
A["Access a name"] --> B["Local scope"]
B --> C{"Found?"}
C -->|Yes| G["Return the corresponding object"]
C -->|No| D["Enclosing: outer function scope"]
D --> E{"Found?"}
E -->|Yes| G
E -->|No| F["Global: module global scope"]
F --> H{"Found?"}
H -->|Yes| G
H -->|No| I["Built-in scope"]
I --> J{"Found?"}
J -->|Yes| G
J -->|No| K["Raise NameError"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Local: local scope
name = "global"
def greet():
name = "local"
print(name)
greet()
Output:
local
Because a local name name exists inside the function, the local binding takes priority during lookup.
3. Enclosing: outer function scope
When functions are defined nested inside one another, the inner function can access names from the outer function.
def outer():
message = "Hello"
def inner():
print(message)
inner()
outer()
Output:
Hello
Here message lives in the enclosing scope of the inner function.
4. Global: global scope
name = "Python"
def greet():
print(name)
greet()
The inner functions has no local name and no available outer function binding, so the lookup continues into the module's global namespace.
5. Built-in: built-in scope
def calculate(values):
return len(values)
print(calculate([1, 2, 3]))
When len in the function has no local or global binding, the lookup continues into the built-in namespace.
6. Name shadowing
If the local namespace contains a name that is identical to a global or built-in name, the local binding takes priority.
For example:
len = 100
print(len)
Here the global name len shadows the built-in function len().
This affects subsequent code:
values = [1, 2, 3]
# This will raise an error, because len has already been bound to an integer
# print(len(values))
In engineering practice, avoid using built-in function names as variable names.
VII. The difference between namespaces and scopes
Namespaces and scopes are closely related, but they are not the same concept.
A namespace answers:
Which object is a given name bound to?
A scope answers:
At which location in the program can that binding be accessed through the name?
For example:
value = "global"
def outer():
value = "outer"
def inner():
value = "inner"
print(value)
inner()
outer()
Here there are several distinct name bindings:
- The
valuein the module global namespace. - The local binding corresponding to the
outerfunction call. - The local binding corresponding to the
innerfunction call.
Although they use the same name, they belong to different namespaces or local binding environments.
1. Namespace vs. Scope Comparison
| Aspect | Namespace | Scope |
|---|---|---|
| Core meaning | Mapping from names to objects | Accessible range of name bindings |
| Focus | Where names are stored | Where names are visible |
| Typical forms | Module dictionaries, class dictionaries | Local, enclosing, global, built-in |
| Main purpose | Avoid name conflicts | Control name lookup |
| Related mechanisms | globals(), locals() |
LEGB, global, nonlocal |
2. An Important Distinction: Class Scope Is Not the Enclosing Scope in Ordinary LEGB
For example:
name = "global"
class User:
name = "class"
def greet(self):
print(name)
user = User()
user.greet()
Output:
global
This is because the namespace in a class definition body does not become the Enclosing scope of ordinary method functions.
The name in the method continues to access the module global name according to normal name lookup rules, and does not automatically look up name in the class namespace.
To access a class attribute, you can use:
class User:
name = "class"
def greet(self):
print(self.name)
You can also access it through the class name:
class User:
name = "class"
def greet(self):
print(User.name)
This distinction is very important for understanding Python's object-oriented mechanics.
VIII. global and nonlocal
Python provides the global and nonlocal keywords to explicitly change the scope of name bindings.
1. global: Declaring a Module Global Name
By default, assigning to a name inside a function makes it a local name of the current function.
For example:
count = 0
def increment():
count = count + 1
This raises UnboundLocalError when executed.
The reason is that because there is an assignment in the function, Python determines that count is a local name, but when it is read on the right side of the assignment, the local binding has not yet been established.
Using global, you can declare that it refers to the module global name:
count = 0
def increment():
global count
count += 1
increment()
print(count)
Output:
1
global affects name binding; it is not a requirement for modifying the contents of an object.
For example:
items = []
def add_item():
items.append("Python")
add_item()
print(items)
Here global is not needed because the function does not rebind items; it only modifies the mutable list object that items refers to.
2. nonlocal: Declaring a Name in an Outer Function
nonlocal is used in a nested function to modify an existing binding in the nearest enclosing function scope.
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
inner()
return count
print(outer())
Output:
2
Without nonlocal, an assignment in the inner function would normally create a new local binding, rather than modify count in the outer function.
3. Differences Between global and nonlocal
| Comparison item | global | nonlocal |
|---|---|---|
| Scope | Module global scope | Enclosing function scope |
| Main use | Modify module-level name bindings | Modify name bindings in an enclosing function |
| Requires an existing binding? | Can create module-level bindings | A suitable binding in an enclosing function must exist |
| Common scenarios | Global configuration or counters | Closure state management |
4. Precautions for Use
globalandnonlocalmust be declared before the relevant name is used in the current code block.nonlocalcannot be used for module-level names.nonlocalcannot directly refer to names in a class namespace.- Modifying the contents inside a mutable object generally does not require
globalornonlocal. - Rebinding names is the main issue these two keywords address.
In engineering development, state should preferably be managed through function parameters, return values, object attributes, or dependency injection, avoiding excessive reliance on global variables.
9. Package Import Mechanism and Namespaces
A package not only contains multiple modules but also participates in Python's hierarchical import mechanism.
1. Package Objects and Module Objects
A package itself is also a type of module object.
For example:
import geometry
print(type(geometry))
print(geometry.__name__)
print(geometry.__package__)
print(geometry.__path__)
A package has the basic attributes of a module object and usually also has a __path__ attribute.
__path__ describes where the package searches for submodules.
Ordinary modules generally do not have __path__.
2. Attribute Binding When Importing Submodules
Assume:
geometry/
├── __init__.py
└── circle.py
Run:
import geometry.circle
After import, it can usually be accessed as follows:
geometry.circle
This is because the import system binds the submodule object to the corresponding attribute name on the parent package.
This can be understood as:
geometry
└── circle
Here, geometry is the parent package and circle is the submodule.
3. Hierarchical Relationship Between Packages and Subpackages
Assume:
company/
├── __init__.py
└── department/
├── __init__.py
└── employee.py
Import:
import company.department.employee
It can be accessed as:
company.department.employee
Each level of package participates in organizing and resolving the full module name.
4. Importing a Parent Package Does Not Mean Automatically Importing All Submodules
For example:
import geometry
This usually only imports and initializes the geometry package itself and does not automatically load all submodules in the directory.
If you need to use circle.py, you should usually import it explicitly:
import geometry.circle
Alternatively, explicitly import and expose the relevant interfaces in geometry/__init__.py.
This helps control package initialization cost and dependencies.
10. Namespace Packages
In addition to traditional regular packages, Python also supports namespace packages (Namespace Package).
A namespace package allows multiple different directories to jointly form the same package.
1. Why Namespace Packages Are Needed
In large projects or plugin ecosystems, the same top-level package may have subpackages provided by multiple independent projects.
For example:
project_a/
└── company/
└── service_a/
└── __init__.py
project_b/
└── company/
└── service_b/
└── __init__.py
If the parent directories of both projects are on the valid import search path, Python can combine the two company directories into a single namespace package.
Then they can be imported separately:
import company.service_a
import company.service_b
2. Characteristics of Namespace Packages
Namespace packages have the following characteristics:
- Does not require the presence of
__init__.py. - Can be made up of multiple directories together.
- The package search path may contain multiple locations.
- Suited to plugin ecosystems and cross-project extension.
- Does not necessarily correspond to a single fixed physical directory.
3. Differences Between Regular Packages and Namespace Packages
| Comparison Item | Regular Package | Namespace Package |
|---|---|---|
__init__.py |
Usually present | Not required |
| Package initialization code | Can be executed | Not executed through a traditional package initialization file |
| Package path | Usually corresponds to one package directory | Can be composed of multiple locations |
| Extension capability | Usually managed by a single package directory | Supports extension across multiple directories |
| Typical use | Conventional project organization | Plugin systems and cross-project extension |
4. The Search Mechanism of Namespace Packages
Namespace packages follow somewhat different lookup rules from regular packages.
When Python looks for a package, if it finds a regular package or module in some location, it may use that result directly; if it only finds candidate directories without __init__.py, it treats them as candidate search locations for a namespace package.
After the search process ends, if no regular package or module with higher priority is found, a namespace package may be created.
Therefore, the constituent locations of a namespace package depend not only on whether the directories exist, but are also affected by the entire module search process.
5. Viewing Namespace Package Paths
You can inspect a package's search locations through __path__:
import company
print(company.__path__)
The path of a namespace package may contain multiple directories.
You can also inspect:
print(company.__spec__)
print(company.__spec__.origin)
A namespace package usually has no single source file location corresponding to it in the traditional sense.
11. Relative and Absolute Imports in Python Packages
Modules inside a package often need to reference modules in the same package or in other packages.
Python provides absolute imports and explicit relative imports.
1. Absolute Imports
Suppose the project structure is:
my_project/
├── main.py
└── app/
├── __init__.py
├── services/
│ ├── __init__.py
│ └── user_service.py
└── utils/
├── __init__.py
└── logger.py
In user_service.py:
from app.utils.logger import get_logger
This is an absolute import, describing the path starting from the top-level package name app.
2. Relative Imports
It can also be written as:
from ..utils.logger import get_logger
The dots indicate a position relative to the current package.
| Syntax | Meaning |
|---|---|
from . import module |
Import a module from the current package |
from .module import name |
Import a name from a module in the current package |
from .. import module |
Import a module from the parent package |
from ..utils import logger |
Import a module from the utils subpackage of the parent package |
from ... import module |
Import a module from the package two levels up |
3. The Boundaries of Relative Imports
Relative imports depend on the package context of the current module.
For example:
from ..utils.logger import get_logger
If you execute it directly:
python app/services/user_service.py
It will usually fail because there is no valid parent package context.
You can use the following from the project root directory:
python -m app.services.user_service
This way of running code by module name establishes the appropriate package context.
4. How to Choose an Import Style
The general recommendation is: