如何解决Python:导入函数时发出“弃用”警告
在文件B.py
中,我有一个函数hello()。该位置已弃用,我将其移至A.py
。
我目前正在这样做:
def hello():
from A import hello as new_hello
warnings.warn(
"B.hello() is deprecated. Use A.hello() instead.",DeprecationWarning
)
return new_hello()
但是在调用该函数时会发出警告。我想在导入函数时发出警告。如果这样导入函数,是否可以发出警告:
from B import hello
B.py
还具有其他一些不被弃用的功能。
解决方法
在函数上使用装饰器应该可以工作,在导入或调用函数时将显示警告。请仔细检查该函数是否在导入时不执行(不应)。
import warnings
import functools
def depreciated_decorator(func):
warnings.warn("This method is depreciated")
@functools.wraps(func)
def wrapper(*args,**kwargs):
return func(*args,**kwargs)
return wrapper
@depreciated_decorator
def test_method(num_1,num_2):
print('I am a method executing' )
x = num_1 + num_2
return x
# Test if method returns normally
# x = test_method(1,2)
# print(x)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。