Skip to content

Properly document WarningMessage interface #139837

@tomerv

Description

@tomerv

Bug report

Bug description:

I wasn't sure if I should open this as a bug, documentation issue, or enhancement request. It's somewhere in between.

The documentation for warnings.catch_warnings() says

If record is True, a list is returned that is progressively populated with objects as seen by a custom showwarning() function (which also suppresses output to sys.stdout). Each object in the list has attributes with the same names as the arguments to showwarning().

This seems to imply that the following code should work:

with warnings.catch_warnings(record=True) as ws:
    warnings.warn("spam")

for w in ws:
    warnings.showwarning(**w.__dict__)

However, it gives the following error:

TypeError: showwarning() got an unexpected keyword argument 'source'

Also, there is an additional class member _category_name which isn't a valid keyword argument for showwarning(). The remaining class members are valid keyword arguments.

I believe there are 2 ways to fix this:

  1. Modify the default showwarning() to support the keyword arguments source and _category_name.
    1a. Variation: add keyword arguments source, and remove the member _category_name from the returned values.
    1b. Another variation: Add a catch-all **kwargs to showwarning().
  2. Update the documentation to clarify the wording. I'm not sure what wording would be better.

Additional consideration: The returned values from catch_warnings(record=True) are warnings.WarningMessage objects, and this type is not documented. Maybe it should be?

CPython versions tested on:

3.11, 3.13

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions