Skip to content

Instantly share code, notes, and snippets.

@kharmabum
Created December 22, 2022 23:44
Show Gist options
  • Save kharmabum/eb91789e8b0332c41dcbaebc82f66709 to your computer and use it in GitHub Desktop.
Save kharmabum/eb91789e8b0332c41dcbaebc82f66709 to your computer and use it in GitHub Desktop.
#!/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