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)