Python:导入函数时发出弃用警告

2024-04-25 21:05:36 发布

您现在位置: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还有一些其他函数,这些函数没有被弃用


Tags: 文件函数frompyimport警告hellonew
1条回答
网友
1楼 · 发布于 2024-04-25 21:05:36

在函数上使用decorator应该可以工作,在导入或调用函数时将显示警告。请仔细检查该函数在导入时是否未执行(不应该执行)

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)

相关问题 更多 >