Show warning when a class is imported in python

前端 未结 4 931
臣服心动
臣服心动 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 12:03

    You could use [Python 3.Docs]: warnings - Warning control, which states (emphasis is mine):

    Changed in version 3.2: DeprecationWarning is now ignored by default in addition to PendingDeprecationWarning.

    so, you'll have to "manually" enable it, otherwise it won't be visible when importing mod00. This way:

    • The warning will be displayed when importing or executing the module
    • The class can be instantiated as well

    mod00.py:

    #!/usr/bin/env python
    
    import warnings
    warnings.filterwarnings("default", category=DeprecationWarning, module=__name__)
    
    print("Module mod00")
    
    
    class Dummy:
        warnings.warn("Dummy class is deprecated", category=DeprecationWarning, stacklevel=2)
    
    
    if __name__ == "__main__":
        print("Execute module mod00")
    

    mod01.py:

    #!/usr/bin/env python
    
    from mod00 import Dummy
    
    
    if __name__ == "__main__":
        print("Execute module mod01")
        dummy = Dummy()
        print(dummy)
    

    Output:

    e:\Work\Dev\StackOverflow\q060486000>sopr.bat
    *** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***
    
    [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" -m mod00
    Module mod00
    e:\Work\Dev\StackOverflow\q060486000\mod00.py:9: DeprecationWarning: Dummy class is deprecated
      class Dummy:
    Execute module mod00
    
    [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" mod00.py
    Module mod00
    mod00.py:9: DeprecationWarning: Dummy class is deprecated
      class Dummy:
    Execute module mod00
    
    [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" -c "import mod00"
    Module mod00
    e:\Work\Dev\StackOverflow\q060486000\mod00.py:9: DeprecationWarning: Dummy class is deprecated
      class Dummy:
    
    [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" -m mod01
    Module mod00
    e:\Work\Dev\StackOverflow\q060486000\mod00.py:9: DeprecationWarning: Dummy class is deprecated
      class Dummy:
    Execute module mod01
    
    

提交回复
热议问题