Stefan Ram wrote:

>   I'm not sure I understand "filterwarnings" correctly.
>   It does not suppress the warning within the "with" statement below.
>   Outside of the "with" statement, it does work, but according
>   to sources it also should work within the "with" statement.
> 
>   Console transcript:
> 
> |Python 3.9....
> |Type "help", "copyright", "credits" or "license" for more information.
> |>>> import warnings
> |>>> with warnings.catch_warnings():
> |...     warnings.filterwarnings("ignore", category=SyntaxWarning)
> |...     print( 1 is 1 )
> |...
> |<stdin>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
> |True
> |>>> warnings.filterwarnings("ignore", category=SyntaxWarning)
> |>>> print( 1 is 1 )
> |True
> 
>   How could I make "filterwarnings" work inside the "with" statement?
>   TIA!

It does work already:

>>> with warnings.catch_warnings():
...     warnings.filterwarnings("ignore", category=UserWarning)
...     warnings.warn("yadda")
... 
>>> warnings.warn("yadda")
<stdin>:1: UserWarning: yadda

The problem is that you picked the wrong category. As SyntaxWarnings are 
issued during compilation you need to trigger a compilation to see the 
effect:

>>> with warnings.catch_warnings():
...     warnings.filterwarnings("ignore", category=SyntaxWarning)
...     exec("1 is 1")
... 
>>> exec("1 is 1")
<string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to