Thursday, April 28, 2022

[FIXED] How to determine the module name to filter a specific Python warning?

Issue

With Python one can filter specific warnings using the following command line syntax:

-W action:message:category:module:line

But how can one determine the correct value for module for a particular warning?

Consider the following example:

Using (pipenv --python 3.6.5 install lxml==4.2.4)

> python -W error -c "from lxml import etree"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "src/lxml/etree.pyx", line 75, in init lxml.etree
  File "src/lxml/_elementpath.py", line 56, in init lxml._elementpath
ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__

If one wanted to ignore only that specific import warning, how does one find the module name to use? None of the following commands appear to be correct. They all still emit the warning.

python -W error -W ignore::ImportWarning:lxml -c "from lxml import etree"
python -W error -W ignore::ImportWarning:lxml.etree -c "from lxml import etree"
python -W error -W ignore::ImportWarning:lxml._elementpath -c "from lxml import etree"
python -W error -W ignore::ImportWarning:etree -c "from lxml import etree"
python -W error -W ignore::ImportWarning:_elementpath -c "from lxml import etree"
python -W error -W 'ignore::ImportWarning:lxml[.*]' -c "from lxml import etree"

Solution

the ImportWarning warnings, in fact, is from import.c, but you need to filter with _frozen_importlib, the stacks in the warning message are incomplete and internal stacks are omitted. you could obtain this info by overridden warnings.showwarning:

import warnings

def showwarning(message, category, filename, lineno, file, line):
    print(filename)

warnings.showwarning = showwarning
warnings.resetwarnings() # allow all warnings

from lxml import etree

you could verify this by:

python -Werror::ImportWarning:_frozen_importlib -c 'import lxml.etree'

btw ImportWarning is ignored by default.



Answered By - georgexsh
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.