Search code examples
pythonwarningssuppress-warningsdeprecation-warning

DeprecationWarning - imp module


Some of my programs work without problem but I get the following error code nevertheless. It doesn't have an effect on the program itself but I'd still like to solve it.

C:\Program Files\JetBrains\PyCharm Community Edition 2019.2.3\helpers\pycharm\docrunner.py:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  import imp

Solution

  • There are a few options that can help you ignore these warnings. I recommend absolutely none of them, other than the last one at the end.

    You can use warnings, either specifically for that line:

    import warnings
    
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",category=DeprecationWarning)
        import imp
    

    Or for everything at the top of your code (might not work sometimes):

    import warnings
    warnings.filterwarnings("ignore", category=DeprecationWarning) 
    import imp
    

    You can even add a modified "shebang" at the start of your code so that would run implicitly:

    #!/usr/bin/env python -W ignore::DeprecationWarning
    import imp
    

    Or you can similarly run your code from the command line with the same argument:

    C:\Users\user>python -W ignore::DeprecationWarning yourfile.py
    

    That last one is possible in PyCharm as well, by editing the arguments in "Run configurations -> Interpreter options" and adding -W ignore::DeprecationWarning

    But all of these options (except for the last one) involve changing your code. And if you're doing that, you might as well do the best thing possible which is to listen to the warning and start working with importlib so you don't have to deal with out-dated code.

    In any case, if you still want to use warnings, the full documentation is here