Python

Deprecation Warning Decorator

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Mark a function as deprecated so callers get a DeprecationWarning the first time it's called. Includes the replacement function name in the message so callers know what to switch to.
Python
Raw
import functools
import warnings

def deprecated(reason: str = "", *, replacement: str | None = None):
    def decorator(fn):
        msg = f"{fn.__qualname__}() is deprecated"
        if replacement: msg += f" — use {replacement}() instead"
        if reason:      msg += f"  ({reason})"

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            warnings.warn(msg, DeprecationWarning, stacklevel=2)
            return fn(*args, **kwargs)
        return wrapper
    return decorator

@deprecated("renamed for clarity", replacement="connect_db")
def open_db():
    pass

open_db()
# DeprecationWarning: open_db() is deprecated — use connect_db() instead (renamed for clarity)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.