Modules🔗
deprecated_module() marks an entire Python module as deprecated by replacing its __class__ with an intercepting wrapper. Every public attribute access on the old module name invokes its FutureWarning path. Standard warning filters can suppress repeated display.
Three patterns are supported:
- Mode 1 warns in place without moving any code.
- Mode 2 redirects attribute access to a replacement module.
- Mode 3 exposes a deprecated module name as a package attribute.
For deprecating individual functions see Functions; for classes see Classes.
When to use deprecated_module()🔗
Reach for deprecated_module() when a module is being replaced or renamed. Every attribute access on the old name invokes the configured warning path automatically.
Place the call at the bottom of the file being deprecated. It reassigns the module's __class__ to an intercepting wrapper and attaches __deprecation_config__ metadata. This lets find_deprecation_wrappers() discover it.
Mode 1 — in-place warn🔗
Use this when you want to keep the module in place and invoke its warning path on every attribute access. Call deprecated_module(__name__, ...) at the bottom of old_calculator.py:
# phmdoctest:skip — old_calculator.py in-place warn template
# old_calculator.py — DEPRECATED API; use new_calculator instead
# NEW API — same functions now live in new_calculator.py
from deprecate import deprecated_module
def add(a: float, b: float) -> float:
"""Add two numbers. Prefer new_calculator.add."""
return a + b
def multiply(a: float, b: float) -> float:
"""Multiply two numbers. Prefer new_calculator.multiply."""
return a * b
# Mark this module deprecated — call once at the bottom.
# name is optional; when omitted it is auto-detected from the caller's __name__.
# Without message_template, the warning reads:
# FutureWarning: The `old_calculator` module was deprecated since v2.0. It will be removed in v3.0.
# With message_template (as below), it replaces the built-in notice entirely:
# FutureWarning: Use `new_calculator` instead.
deprecated_module(
deprecated_in="2.0",
remove_in="3.0",
message_template="Use `new_calculator` instead.",
)
import old_calculator; old_calculator.add(1, 2) invokes the FutureWarning path and returns the result. Every public attribute access — real functions, classes, constants — takes that path because deprecated_module() replaces the module's __class__ with an intercepting wrapper. Standard filters can suppress repeated display.
attrs_mapping also works here without a target. {"old_name": "new_name"} serves the module's own new_name for old_name, even when old_name still exists in the module, and {"gone": None} makes gone raise AttributeError. Use it to rename or remove a module attribute in place.
Call it at module top level when omitting name. Auto-detection reads the caller frame's __name__. This only names the intended module when the call sits directly in the module body. Calling without name from a function or class body (e.g. a _setup_deprecations() helper) raises TypeError. The frame's __name__ would point at the enclosing module and silently deprecate all of it. Pass name explicitly to call from any other scope.
Mode 2 — redirect to a replacement module🔗
Use this when you rename an entire module. Attribute lookups missing from the old module's __dict__ are forwarded to new_calculator, so callers get both a warning and the correct value. Real attributes already defined in the old module (functions, constants) are served from its __dict__ directly; they warn but are not forwarded.
Redirect cycle detection uses context-local state and restores the prior state when the outer lookup finishes. Cyclic redirects raise AttributeError rather than recursing indefinitely. Contexts copied during a lookup can resolve the same name again after that lookup finishes. This applies whether it returned a value or raised an exception.
# phmdoctest:skip — CI template; new_calculator is not installed
# old_calculator.py — DEPRECATED API — redirect to new_calculator
# NEW API — same functions live in new_calculator.py
from deprecate import deprecated_module
# Load the replacement module to attach as redirect target
import new_calculator as _new_calculator
deprecated_module(
__name__,
target=_new_calculator, # every unknown attr forwarded here
deprecated_in="2.0",
remove_in="3.0",
message_template="Use `new_calculator` instead.",
)
Now import old_calculator; old_calculator.add(1, 2) invokes the FutureWarning path and returns the result from new_calculator.add; standard warning filters can suppress repeated display. The attrs_mapping parameter lets you rename specific attributes during the redirect:
# phmdoctest:skip — attrs_mapping continuation; requires new_calculator
# Map old attr name to new attr name, or to None to raise AttributeError.
# Keys are the names callers use today (the original API names).
from deprecate import deprecated_module
deprecated_module(
__name__,
target=_new_calculator,
attrs_mapping={"compute": "add", "beta_feature": None},
deprecated_in="2.0",
remove_in="3.0",
)
old_calculator.compute invokes the warning path and forwards to new_calculator.add (the function was renamed). old_calculator.beta_feature invokes it and raises AttributeError (no replacement). Standard filters can suppress repeated display; all other names fall through to new_calculator.
Mode 3 — parent alias via deprecated_instance🔗
When reorganising a package, use deprecated_instance() in the parent __init__.py to keep the old sub-module name accessible as a parent-package attribute. This does not require a new API; it reuses the existing proxy mechanism.
# phmdoctest:skip — CI template; my_package is not installed
# my_package/__init__.py
import my_package.new_calculator as _new_calculator
from deprecate import deprecated_instance
# DEPRECATED API — expose `old_utils` as a package attribute pointing to new_calculator
old_utils = deprecated_instance(
_new_calculator,
name="old_utils",
deprecated_in="2.0",
remove_in="3.0",
message_template="Use `my_package.new_calculator` instead.",
)
import my_package; my_package.old_utils.add(1, 2) invokes the FutureWarning path on the first attribute access and forwards to new_calculator; standard filters can suppress display.
Limiting warning volume with num_warns🔗
By default deprecated_module() delivers a warning on every public attribute access, matching its behavior before num_warns existed. Standard warning filters can still suppress repeated display at the same location.
Pass num_warns to cap deliveries with the same semantics as @deprecated's num_warns. The default is -1 (unlimited) instead of 1 until v1.0. It then becomes 1 like everywhere else (see the box below).
# phmdoctest:skip — old_calculator.py in-place warn template, budgeted variant
from deprecate import deprecated_module
deprecated_module(
deprecated_in="2.0",
remove_in="3.0",
num_warns=1, # warn once per process, then stay silent
)
num_warns |
Deliveries |
|---|---|
0 |
It never delivers a warning. |
A positive N |
It delivers exactly N warnings. |
-1 (the default) |
It delivers on every access. |
The counter is one budget shared across every attribute name on the module. There is no per-attribute counter the way deprecated_class's attrs_mapping gets one.
-1 avoids budget locking but still performs metadata lookup and warning handling. Use a finite budget for a worker service whose custom stream or warning filter would otherwise record repeated accesses.
Changes in v1.0
Omit stream to deliver the module warning through warnings.warn (the default; help(deprecated_module) shows it as <warnings.warn>). An explicit stream=None does the same today, but emits a FutureWarning at the deprecated_module(...) call.
In v1.0 stream=None will silence the module warning, as it already does for @deprecated, deprecated_class and deprecated_instance. In the same release the num_warns default changes from -1 to 1. Pass num_warns=-1 explicitly to keep a warning on every access.
A missing deprecated_in warns at install time. deprecated_module emits a UserWarning ("has no deprecated_in set") when deprecated_in is empty. A message_template silences it, as for @deprecated, deprecated_class and deprecated_instance; stream=None does not yet, because the module keeps delivering its warning until v1.0. Otherwise pass deprecated_in.
Existing module hooks and repeat calls🔗
The install itself can emit three more UserWarning notices:
- Existing
__getattr__. A module that already defines a PEP 562__getattr__keeps it: lookups the wrapper cannot serve are chained to it, and the install warns that it is chaining. - Repeat call. An identical repeat call is silent. A repeat with a different configuration is ignored with a warning, and the original configuration stays.
- Custom
__class__. A module whose__class__is already custom, for example one installed by a lazy loader, is overwritten with the wrapper and its prior behaviour is lost; the install warns about it.
Star imports also warn🔗
Star imports (from old_calculator import *) still trigger the deprecation warning. CPython's IMPORT_STAR bytecode calls getattr(module, name) for each public name being pulled in. That call routes through the same __getattribute__ interception installed by deprecated_module().
A FutureWarning therefore fires once per pulled-in public name, exactly as it would for old_calculator.add(1, 2). A PEP 562 module-level __getattr__ hook fires only for missing names. Star imports can invoke it for dynamic names listed in __all__, but not for existing attributes.
Audit integration🔗
find_deprecation_wrappers() discovers modules marked with deprecated_module() the same way it discovers function and class wrappers — by reading the __deprecation_config__ attribute attached to the module object:
# phmdoctest:skip — CI template: replace my_package with your actual package
import my_package
from deprecate import find_deprecation_wrappers
deprecated_items = find_deprecation_wrappers(my_package)
module_items = [r for r in deprecated_items if r.api_type == "module"]
Fatal deprecations🔗
deprecated_module(..., as_exception=True) turns every public attribute access on the module into a raised DeprecatedError — see Fatal deprecations for the full contract, including the process-wide DEPRECATE_AS_EXCEPTIONS switch. It ignores num_warns (every access raises, not just the first) and does not depend on stream.
Tools that walk module attributes
A module is the broadest surface this feature covers, so expect the blast radius to match. Tools that walk module attributes stop at a fatal module rather than skipping it. This includes pytest collection, Sphinx autodoc, pickle, and copy.
pyDeprecate's own audit is unaffected. find_deprecation_wrappers() and the pydeprecate CLI read the module's __dict__ rather than going through attribute access. A fatal module therefore still appears in discovery and reports like any other.
See also🔗
- Start with Use Cases overview for a guided tour of all deprecation patterns.
- Functions covers deprecating individual functions and methods.
- Classes covers class, Enum, dataclass, and instance deprecation.
- Use Audit Tools to enforce removal deadlines and detect deprecation chains in CI.
- Troubleshooting covers common errors and fixes.
Next: Advanced — docstring updates, args_extra, testing helpers, class/static methods, generators.