Limitations and non-goals🔗
pyDeprecate favours a small API over covering every corner of Python. This page lists the corners it deliberately does not cover, so you can recognise them before they surprise you. Each entry states the behaviour in one or two sentences and links to the section with the details and the workaround.
Async and generators🔗
- Callable objects with
async def __call__are not detected as coroutine functions.inspect.iscoroutinefunctiondoes not look at__call__, and@deprecatedrejects a plain callable instance withTypeError, so such an object cannot serve as anasync defsource. Define a thinasync defthat awaits the object and decorate that. See functools.partial and callable wrappers. - Async and sync targets are not interchangeable in both directions. An
async defsource may forward to a sync target, which is called directly without being awaited. A sync source whose target is a coroutine function raisesTypeErroron the first call, because a sync wrapper cannot await it. Declare the sourceasync def. - A
@types.coroutinegenerator keeps the plain wrapper. A generator-based coroutine is a generator function thatawaitaccepts only because its own code object carries theCO_ITERABLE_COROUTINEflag, which a generator wrapper lacks, so@deprecatedgives it the plain function wrapper: the warning fires at the call rather than on the first step, andinspect.isgeneratorfunctionreportsFalsefor the wrapper. - A deprecated generator raises its argument errors on the first step, not at the call. A native generator function called with the wrong number of arguments raises
TypeErrorat once, but its deprecated wrapper accepts any arguments and only creates the generator, so that arityTypeError(in pyDeprecate's own wording), and aFailed mappingerror from a forwarding target, raise on the firstnext()orasync forstep. See Deprecating generator functions. - Cycle detection is lazy. A
target=chain that loops back on itself is not caught at decoration time; theRuntimeErrorfires when a wrapper in the cycle is first called. For generator wrappers it fires on the firstnext()orasync forstep, because calling a generator wrapper runs nothing. The same error fires when a replacement recurses through the deprecated name while the wrapper is still on the call path (for a generator, before its firstyield), so recurse through the replacement's own name instead. See the cycle error.
Proxies (deprecated_instance, deprecated_class)🔗
- Item writes never warn.
proxy["key"] = valueanddel proxy["key"]pass through silently, like attribute writes, and they honourskip_if. Withread_only=Truethey raiseAttributeErrorunlessskip_ifis active. See deprecated_instance. read_onlycovers only the standard mutators. Besides writes through the proxy, it blocks the collection methodsappend,clear,discard,extend,insert,pop,remove,setdefault,updateandadd. A custom method such asregister()orreload()still mutates the wrapped object. See read_only troubleshooting.- A proxy over a
strorbytesvalue claimsos.PathLike. A proxy carries only the protocols the wrapped object supports, socallable(),Iterator,Awaitableand the other structural ABCs answer as for the object itself. The one exception is text:int(),float(),complex()andos.fspath()parsestrandbyteswithout a dunder on the type, and the proxy keeps those conversions so a deprecated"8080"or path string still converts. That makes such a proxy reportos.PathLikeandtyping.SupportsInttoo. Check the type of the unwrapped object when you use one of those two checks as a guard. - A proxy's protocols are fixed when it is created. The proxy picks the protocols it serves (calling, iteration,
len(),in, subscript, hashing, operators) from the type of the wrapped object, and of its replacement, at the moment it is constructed. A method the type gains afterwards, such as a__call__patched in later or a magic method set on aMockafter wrapping, does not reach that proxy:callable(obj)can beTruewhilecallable(proxy)isFalse. Up to v0.14 every proxy forwarded every protocol. Finish setting up the object before you wrap it, or wrap it again after changing its type. - A class proxy cannot be pickled by reference when it replaces the class's own name. When
deprecated_classrebinds the module-level name of the decorated class,picklefinds the proxy where it expects the class, so pickling the class alias itself raisesPicklingError. This covers the class object only: instances of a class deprecated in place pickle and load as instances of the original class, and neither step warns. A payload pickled before the in-place deprecation loads only while its recordedmodule.qualnamestill names the real class; once that name is rebound to the proxy, loading fails. Re-pickling before deprecating does not help, because a payload written while the name is still bound to the real class names that class directly; load such payloads through apickle.Unpickler.find_classoverride that unwraps the proxy. This includes exception andOrderedDictsubclasses, whose inherited__reduce__calls the class. A class that defines its own__reduce_ex__keeps its own pickling, so members of an Enum deprecated in place still raisePicklingError.deprecated_instanceproxies pickle fine. See copy, deepcopy and pickle. - Pickled instances of a class deprecated in place load only while the deprecation is in place. Their payload names one of pyDeprecate's rebuild helpers instead of the class, so the loading process needs pyDeprecate installed, and once the deprecation is removed the helpers refuse the plain class with
AttributeError. The helper names stay stable across releases, so upgrading pyDeprecate is safe. To migrate stored instances, load them while the deprecation is in place, then in the migration process set the module attribute back to the real class and re-pickle; re-pickling while the proxy still holds the name writes helper-dependent payloads again. See loading pickled instances. - The class of a proxy cannot be pickled.
type(proxy)is a generated subclass of_DeprecatedProxythat carries the proxy's protocols and borrows the base class's module and name, sopickle.dumps(type(proxy))raisesPicklingError: the borrowed name resolves to a different class. pyDeprecate v0.14 pickled the proxy class by reference. Pickling the proxy itself is unaffected. To detect a proxy, checkisinstance(obj, DeprecationProxy)rather than storing or pickling its class. - A replacement object changes type checks at once. With
deprecated_instance(old, target=new),isinstance, hashing and the served protocols follownewas soon as the deprecation ships, not at removal: a tuple constant replaced by a list is no longer hashable through the old name. Keep the replacement the same type as the old object, or a subclass. See Serving a replacement object. attrs_mappingon an instance covers attributes, not keys.deprecated_instance(settings, attrs_mapping={"old": "new"})redirectssettings.old; a deprecated key of a dict (settings["old"]) cannot be renamed through the proxy.- A
bool,Noneor a module cannot be a replacement object.target=Nonemeans no replacement;target=True,target=Falseand a module raiseTypeError. To replace aboolconstant, wrap the new value itself (deprecated_instance(NEW_FLAG, name="OLD_FLAG", ...)); redirect a module withdeprecated_module. args_mappingpasses a renamed value by keyword when the called object hides its signature. To place a value renamed onto a positional-only parameter positionally,deprecated_instanceanddeprecated_classread the signature of the object they call once, when the proxy is built. A builtin such asiterexposes none, and an object whose__signature__raises is treated the same way, sodeprecated_instance(iter, args_mapping={"collection": "object"})passesobject=by keyword and the call raises the builtin's ownTypeError(iter() takes no keyword arguments). Building the proxy does not warn about this, because builtins such asmaxandminhide their signature too yet accept the renamed keyword (key=). Rename the arguments of such a builtin in a small Python function and wrap that function instead.cached_propertywarns at most once per instance. The cache is filled by the first read, so later reads of that instance never reach pyDeprecate andnum_warnscannot raise the count. Withnum_warns=-1every instance warns on its first read; the defaultnum_warns=1budget is shared by all instances, so only the first one warns. See Properties.
Configuration🔗
skip_ifmust return a strictbool. A truthyintor a string raisesTypeError; wrap the result inbool(...). See theskip_iferror.- A bound target does not work for a classmethod source. A bound target such as
target=YourClass.methodworks only for a source that is not a classmethod; for a genuine classmethod source it fails, because the bound target has no receiver parameter and the source's receiver argument is rejected. Inside the class body pass the raw descriptor (target=method) instead. See Class methods and static methods. - A classmethod target cannot tell a plain or static source from a classmethod. A static source written
@deprecated(...)above@staticmethodis rejected at decoration, but a plain function, or a static source written@staticmethodabove@deprecated(...), looks like a classmethod source. Its first argument, or that parameter's default when the call leaves it out, is forwarded as the replacement's class: a value that is not a class raisesTypeErrorbefore any warning, but a class passed there or given as the default is forwarded as the receiver. Make the source a@classmethod, or give a static source a bound target such astarget=YourClass.method. See Class methods and static methods. - An
as_exceptions()scope reaches a new thread only if the interpreter copies the context. The scope is local to the current thread andasynciotask, and tasks created inside it inherit it. Whether a thread started inside the block inherits it depends on the interpreter, so run the thread's target throughcontextvars.copy_context().run(...)when it must. Inside a scopedeprecate.AS_EXCEPTIONSstill reports the global value, so do not read it to detect a scope. - An
as_exceptions()scope held across a generatoryieldapplies to the consumer. A generator or async generator runs in its consumer's context, so while it is suspended insidewith as_exceptions():the consumer's own code is fatal too, and if the generator is closed from another task (aclose()elsewhere, garbage collection) the scope stays open in the consumer's context. Open and close the scope within one step of the generator. See The global switch.
Static checkers🔗
- Only a literal
warnings.deprecatedis visible to type checkers. PEP 702 tools recognise the decorator by name, so deprecations that pyDeprecate applies at runtime are invisible to mypy, pyright and IDEs. Stack a literalwarnings.deprecated(ortyping_extensions.deprecated) on top as shown in Static type checkers (PEP 702); for classes see PEP 702 static checkers.
Audit tooling🔗
- The Python static API shares the CLI
--staticblind spots.find_deprecation_wrappers_static()(since 0.16) returns aStaticScanResult: read.gapsfor recognized unresolved settings and unaudited source, even when.wrappersis empty. Dynamic forms such as wrappers built in loops or throughgetattr,importliborexeccan remain invisible without a gap, so empty.gapsdoes not prove complete coverage. Rows are approximations with stand-in targets that raiseTypeErrorwhen called. See scanning from Python without importing and CLI static mode. - The full audit imports the package it scans. Its module-level code runs and its runtime dependencies must be installed in the scanning environment, so the import-mode remote pre-commit hooks only suit packages without such dependencies; use a
repo: localhook otherwise. See Audit Tools and the CLI reference. - CLI
--staticcoversexpiryandpolicyonly, and only what the source spells.pydeprecate expiry --staticandpolicy --staticread the source withast, socheck,chains,allandstatus, which need the imported wrappers, have no static mode. A setting computed at runtime, held in a name bound more than once, or splatted from anything but a module-level dict literal is reported as anot statically resolvablegap rather than checked, and a gap does not fail the run. Static mode cannot see wrappers built in loops or throughgetattr,importliborexec, a proxy built from the private_DeprecatedProxydirectly, or a deprecated object or configured decorator imported from outside the scanned package, and it reads atargetimported from outside the package as a replacement even when it holdsNoneor aTargetModemember; members inherited from a base class outside it are a gap. Its--report-jsontable names a replacement by its source text. See Static mode. - CLI scans are per package, never per file. A single
.pypath is rejected withFile paths are not supported, and a directory holding two or more top-level packages is rejected as well, so "scan only the files changed in this commit" is not available. Pass the package directory or an importable name. See Path formats. - The GitHub Action's
install: truere-pins pyDeprecate. The default installs pyDeprecate from the action's own ref into the job's Python, replacing the version your job already had. Setinstall: falsewhen your project pins its own version. See GitHub Action.