Python: Issue Deprecation warning when importing a function

Question:

in a file B.py I have a function hello(). The location is deprecated and I moved it to A.py.

Currently I do:

def hello():
    from A import hello as new_hello
    warnings.warn(
        "B.hello() is deprecated. Use A.hello() instead.",
        DeprecationWarning
    )
    return new_hello()

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:

from B import hello

B.py also has some other functions, which are not deprecated.

Asked By: PascalIv

||

Answers:

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).

import warnings
import functools

def deprecated_decorator(func):
    warnings.warn("This method is depreciated")

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@deprecated_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)
Answered By: Joseph
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.