Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to suppress deprecation warnings

Tags:

python

django

In my Django application, when I import one third party library, I get this warning in the console:

the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses

If however I do the import inside Python shell, then everything is ok. I want to achive the same behaviour in Django. This is what I've tried based on answers in other OS threads:

import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)

The above code results in another error message, that says that RemovedInDjango110Warning does not exists. I also tried this:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

from third_party_lib import some_module

But still I get the very same error message. So, it seems like all previous answers to this problem got outdated. And we need some fresh fix. Thanks!

I also tried this:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    from third_party_lib import some_module

But it has no effect.

like image 572
Jacobian Avatar asked Dec 06 '16 10:12

Jacobian


1 Answers

There are a couple of issues with the code you've tried. If you want to filter PendingDeprecationWarning, then you should use PendingDeprecationWarning in your code. Your code is using DeprecationWarning and RemovedInDjango110Warning, which are different warnings. Secondly, the fxn() function in the docs is an example function that creates a warning. It doesn't make sense to include it in your code.

You can either filter all pending deprecation warnings

import warnings
warnings.simplefilter("ignore", category=PendingDeprecationWarning)

However this might hide pending deprecations in your own code that you should fix. A better approach would be to use a context manager, to filter out warnings when importing the third-party lib.

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=PendingDeprecationWarning)
    from third_party_lib import some_module
like image 103
Alasdair Avatar answered Oct 05 '22 08:10

Alasdair