-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathdeprecated.py
More file actions
51 lines (44 loc) · 1.43 KB
/
deprecated.py
File metadata and controls
51 lines (44 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
A decorator to mark functions as deprecated.
When the function is called, a DeprecationWarning is emitted.
Compatible with Python 2.7+ and Python 3.x.
"""
import functools
import warnings
def deprecated(reason=None):
"""
Decorator to mark functions as deprecated.
Emits a DeprecationWarning when the function is called.
Args:
reason (str, optional): Reason for deprecation. Defaults to None.
Usage:
@deprecated("Use another_function instead.")
def old_function(...):
...
"""
def decorator(func):
message = "Call to deprecated function '{}'.{}".format(
func.__name__,
" " + reason if reason else ""
)
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # show warning every time
try:
warnings.warn(
message,
category=DeprecationWarning,
stacklevel=2
)
return func(*args, **kwargs)
finally:
warnings.simplefilter('default', DeprecationWarning) # reset filter
return wrapped
# Support both @deprecated and @deprecated("reason")
if callable(reason):
# Used as @deprecated without arguments
func = reason
reason = None
return decorator(func)
else:
return decorator