Use as a context manager
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?
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.