Show warning when a class is imported in python

前端 未结 4 924
臣服心动
臣服心动 2021-01-13 11:52

I have a class in a different module and I want to show a DeprecationWarning when that class is imported. What will be the right way to do so?

module 1

4条回答
  •  别那么骄傲
    2021-01-13 11:55

    In your module1.py's Test class. add a warning in your init method:

    import warnings
    
    
    class Test:
        def __init__(self):
            warnings.warn('This class is deprecated', DeprecationWarning)
    

    This will give you the below output, where if you hover on Test, you'll see a warning.

    For that, you'll have to initialize the Test class.

    If you want to show a warning on the import statement, you can call the warning in the module1.py file itself. However, that will happen for all your Classes in your module1.py file if you import them.

提交回复
热议问题