in a file B.py
I have a function hello(). The location is deprecated and I moved it to A.py
.
Currently I do:
JavaScript
x
8
1
def hello():
2
from A import hello as new_hello
3
warnings.warn(
4
"B.hello() is deprecated. Use A.hello() instead.",
5
DeprecationWarning
6
)
7
return new_hello()
8
but this issues the warning when the function is called. I want to issue the warning when the function is imported. Is it possible to issue a warning if a function is imported like this:
JavaScript
1
2
1
from B import hello
2
B.py
also has some other functions, which are not deprecated.
Advertisement
Answer
Using a decorator on the function should work, the warning will be shown when the function is imported or called. Please double check that the function is not executed on import (it shouldn’t be).
JavaScript
1
21
21
1
import warnings
2
import functools
3
4
def deprecated_decorator(func):
5
warnings.warn("This method is depreciated")
6
7
@functools.wraps(func)
8
def wrapper(*args, **kwargs):
9
return func(*args, **kwargs)
10
return wrapper
11
12
@deprecated_decorator
13
def test_method(num_1, num_2):
14
print('I am a method executing' )
15
x = num_1 + num_2
16
return x
17
18
# Test if method returns normally
19
# x = test_method(1, 2)
20
# print(x)
21