Created
December 22, 2022 23:44
-
-
Save kharmabum/eb91789e8b0332c41dcbaebc82f66709 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# See https://stackoverflow.com/a/40301488 | |
import functools | |
import inspect | |
import warnings | |
string_types = (type(b''), type(u'')) | |
def deprecated(reason: str = None, force_warning: bool = False): | |
""" | |
This is a decorator which can be used to mark functions | |
as deprecated. It will result in a warning being emitted | |
when the function is used. | |
""" | |
def wrap_decorator(func): | |
obj_type = 'class' if inspect.isclass(func) else 'function' | |
message = f'Call to deprecated {obj_type} {func.__name__}' | |
if reason: | |
message += f': {reason}' | |
@functools.wraps(func) | |
def func_wrapper(*args, **kwargs): | |
# override warning filter | |
if force_warning: | |
warnings.simplefilter('always', DeprecationWarning) | |
warnings.warn( | |
message, | |
category=DeprecationWarning, | |
stacklevel=2 | |
) | |
# reset warning filter | |
if force_warning: | |
warnings.simplefilter('default', DeprecationWarning) | |
return func(*args, **kwargs) | |
return func_wrapper | |
return wrap_decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment