typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

`warnings.filter` has incorrect type hints for message and module

Open aaronzo opened this issue 1 year ago • 1 comments

Bug report

Bug description:

the message and module fields in warnings.filters type-check as strings but can be of type re.Pattern:

import warnings
from typing import TYPE_CHECKING

warnings.filterwarnings("ignore", message="hello.+", module="somemod")
if TYPE_CHECKING:
    reveal_type(warnings.filters)  # Sequence[tuple[str, str | None, type[Warning], str | None, int]]

[type(x) for x in warning.filters[0]]  # (<class 'str'>, <class 're.Pattern'>, <class 'type'>, <class 're.Pattern'>, <class 'int'>)

CPython versions tested on:

3.12

Operating systems tested on:

Linux

aaronzo avatar Oct 16 '24 23:10 aaronzo

In fact, it seems it's always an re.Pattern (if not None). PR welcome!

srittau avatar Oct 18 '24 10:10 srittau

Had a look in the codebase and found this ominous comment next to the relevant line: https://github.com/python/typeshed/blob/a6fb689ff163d799dbf30871479c9fc8b5165647/stdlib/warnings.pyi#L28

Not sure why this comment is here, or why it's a bad idea to correct a type for an attribute (which is public by naming convention) whether it's documented or not.

aaronzo avatar Oct 21 '24 11:10 aaronzo

"mutate" here probably means you shouldn't mutate it at runtime (e.g., append to the list), not that we can't fix the type. Please do mutate the type so it's correct.

JelleZijlstra avatar Oct 21 '24 11:10 JelleZijlstra

Opened #12866 :)

aaronzo avatar Oct 21 '24 11:10 aaronzo

Was just playing around with this and noticed that the filters when you start an interpreter include:

('default', None, <class 'DeprecationWarning'>, '__main__', 0)

So it seems that in face you can have a string in the list @srittau - so we might have to amend this. I wonder why this one filter has a different type...

aaronzo avatar Oct 30 '24 23:10 aaronzo