Skip to content

warnings.simplefilter("once") emits the same warning once per module #159792

Description

@JelleZijlstra

The "once" filter should suppress repeated warnings with the same message and category, regardless of module or line number (documentation). However, CPython emits the warning again when it originates in another module:

import types
import warnings

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("once")
    for name in ("module_a", "module_b"):
        module = types.ModuleType(name)
        exec("import warnings\nwarnings.warn('same warning')", module.__dict__)

print(len(caught))

Expected: 1
Actual: 2

Reproduced on CPython 3.16.0a1+dev, commit 7756fc0.

In Python/_warnings.c, the "once" branch uses the supplied per-module registry, falling back to the global once registry only when no registry is supplied. The pure-Python implementation uses the global onceregistry and correctly emits only one warning.

This is a longstanding behavior (since 2008) and changing it might be disruptive. On the other hand, currently it seems once is not meaningfully different from module.

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    and removed on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions