[Python] Filtering based on custom warning categories

Discussão em 'Python' iniciado por Stack, Agosto 18, 2025.

  1. Stack

    Stack Membro Participativo

    In addition to pre-existing warning categories, users can define their own warning classes, such as in the code below:

    $ cat mwe.py
    #!/usr/bin/env python3.5

    import warnings
    import pprint

    class ObnoxiousWarning(UserWarning):
    pass

    for i in range(3):
    print(i)
    warnings.warn("I don't like this.", ObnoxiousWarning)


    When invoking Python, the -W flag controls how to filter warnings. But when I try to get it to ignore my freshly minted warning category, I'm told the filter is ignored:

    $ python3.5 -W ignore::ObnoxiousWarning ./mwe.py
    Invalid -W option ignored: unknown warning category: 'ObnoxiousWarning'
    0
    ./mwe.py:11: ObnoxiousWarning: I don't like this.
    warnings.warn("I don't like this.", ObnoxiousWarning)
    1
    2


    How can I use the commandline to insert a filter for custom warning categories (as opposed to all UserWarnings or filtering based on the warning message, which I can do)?

    Edit 2018-11-29: See Issue 66733: -W option cannot use nonstandard categories, still open as of 2025-08-18.

    Continue reading...

Compartilhe esta Página