Induane
Induane

Reputation: 2042

Cannot suppress warnings that are executed during an import call

I'm unable to filter warnings in Python when they're emitted as part of an import. I've tested the following with Python3.8.

This works:

File A:

import warnings

def old_func():
    warnings.warn("This is an old function.")
    pass

File B:

import warnings
from file_a import old_func

warnings.simplefilter("ignore")
old_func()

The warning message is suppressed as expected. But if I change File A like this:

import warnings

def old_func():
    warnings.warn("This is an old function.")
    pass

old_func()

It stops working. I assumed that was because I wasn't setting the filter before the import so I changed File B as follows:

import warnings
warnings.simplefilter("ignore")
from file_a import old_func
old_func()

And still no dice. The warning is emitted no matter what I do. I've also tried the catch_warnings() context manager as follows:

import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    from file_a import old_func
    old_func()

The warning is still emitted. If the warning is emitted during an import there seems to be no way of ignoring it.

I've done some hacky things like temporarily making stderr and stdout in-memory file-like-objects temporarily and that works but it's terrible. I'd like to find a way to do this with reasonable machinery.

Since this is for a command line tool with an entry-point created with setuptools, it's quite a pain to package it in a way that adds a -W option to the interpreter for end users.

A side update: I've confirmed this works on Python 3.6 and does not work on Python 3.8.

Upvotes: 1

Views: 865

Answers (1)

Lenormju
Lenormju

Reputation: 4368

Thanks for the minimal reproducible examples !

I followed your examples, running them each time. But I did not observe the same thing than you :

# file: a.py
import warnings

def old_func():
    warnings.warn("This is an old function.")
    pass

old_func()
# file: b.py
import warnings
warnings.simplefilter("ignore")
from a import old_func
old_func()

does not emit the warning for me, on Windows CPython 3.6.8. Can you check again ?

I assumed that was because I wasn't setting the filter before the import so I changed File B as follows looks very reasonable to me

The last version of your A file works too (i.e. the warning is not displayed)

Upvotes: 1

Related Questions