deprecated icon indicating copy to clipboard operation
deprecated copied to clipboard

Use as a context manager

Open jmehnle opened this issue 2 months ago • 1 comments

I love this package. I'm wondering if there's a way to use deprecated as a context manager inside a function? The reason is that there is only certain behavior of a function that is deprecated, and this is determined dynamically. So basically I have a if statement inside my function, and only when its condition is satisfied will the deprecated behavior run. Is the only solution to define a nested function to run conditionally, and decorate it as deprecated? Could you be convinced to support a context manager that can be used to wrap local logic that's not a dedicated function?

jmehnle avatar Nov 13 '25 10:11 jmehnle

Thank you, if I understand you clearly, what you wish is something like that:

def my_function_desired(use_legacy=False):
    # Common setup code

    if use_legacy:
        # Hypothetical syntax - doesn't currently exist
        with deprecated(version='2.0.0', reason="Use the new behavior instead"):
            # Running deprecated behavior
            result = "old result"
    else:
        # Running new behavior
        result = "new result"
    
    # Common cleanup code
    return result

While context manager support is an interesting idea, for your use case where only specific code paths within a function are deprecated, the simplest solution is to use warnings.warn() directly:

import warnings
from deprecated import DeprecatedWarning

def my_function(use_legacy=False):
    # Common setup code
    
    if use_legacy:
        warnings.warn(
            "The legacy behavior is deprecated since version 2.0.0. "
            "Use the new behavior instead.",
            category=DeprecatedWarning,
            stacklevel=2
        )
        # Running deprecated behavior
        result = "old result"
    else:
        # Running new behavior
        result = "new result"
    
    # Common cleanup code
    return result

This approach gives you full control over when the deprecation warning is issued based on runtime conditions, without the overhead of defining nested functions. The stacklevel=2 parameter ensures the warning points to the caller of your function rather than the warning line itself.

laurent-laporte-pro avatar Nov 13 '25 10:11 laurent-laporte-pro