【问题标题】:Python: Issue Deprecation warning when importing a functionPython:导入函数时发出弃用警告
【发布时间】:2020-09-22 08:10:57
【问题描述】:

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 还有一些其他的功能,没有被弃用。

【问题讨论】:

    标签: python module warnings deprecated


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2017-08-22
      • 2016-09-30
      • 2018-07-15
      • 2022-07-02
      • 1970-01-01
      相关资源
      最近更新 更多