Skip to content

warnings.deprecated should support instances as input #138165

@RonnyPfannschmidt

Description

@RonnyPfannschmidt

Feature or enhancement

Proposal:

i'm working on a library that allows to manage the life-cycle of deprecations

its using different warning types based on different contexts and is heavily relying on warnings.warn... supporting passing instances or strings

from deprecator import Deprecator

deprecator = Deprecator.for_package("my_package")

# depending on  the version of package and gone_in/warn_in this will be a PendingDeprecation, a Deprecation or a PassedDeprecation as defined in deprecator (Passed deprecations will auto register for triggering errors)


OLD_FEATURE = deprecator.define("Myfeature", warn_in="25.02.0", gone_in="26.05.0", repacement="new feature)


def my_code(...):
   warnings.warn(OLD_FEATURE)

i'd like to be able to do


@warnings.deprecated(OLD_FEATURE)
def my_code(...):
  ...

however currently warnings.deprecated is defined in terms that only allow a string

i'm aware of

cpython/Lib/_py_warnings.py

Lines 817 to 833 in fd8f42d

def _deprecated(name, message=_DEPRECATED_MSG, *, remove, _version=sys.version_info):
"""Warn that *name* is deprecated or should be removed.
RuntimeError is raised if *remove* specifies a major/minor tuple older than
the current Python version or the same version but past the alpha.
The *message* argument is formatted with *name* and *remove* as a Python
version tuple (e.g. (3, 11)).
"""
remove_formatted = f"{remove[0]}.{remove[1]}"
if (_version[:2] > remove) or (_version[:2] == remove and _version[3] != "alpha"):
msg = f"{name!r} was slated for removal after Python {remove_formatted} alpha"
raise RuntimeError(msg)
else:
msg = message.format(name=name, remove=remove_formatted)
_wm.warn(msg, DeprecationWarning, stacklevel=3)
and intentional choose a new warning subclass to be registered for errors, as i want to ensure test suites can keep running with records of the issue instead of failures plus enable a work-flow where dead code removal happens after dysfunction sets in so that users have the possibility of a informed workaround while mitigating

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions