Skip to content

wsgiref.headers.Headers.__setitem__ deletes the old header before validating the new value #158225

Closed

Description

@Tony123-tech

In Lib/wsgiref/headers.py, Headers.setitem deletes the existing
header before validating the new name and value:

def __setitem__(self, name, val):
    """Set the value of a header."""
    del self[name]
    self._headers.append(
        (self._convert_string_type(name, name=True),
         self._convert_string_type(val, name=False)))

If _convert_string_type raises (for example when val is not a string),
the old header has already been removed and the new one is never added,
so the header disappears entirely.

Reproduction:

from wsgiref.headers import Headers
h = Headers([("Content-Type", "text/html")])
try:
    h["Content-Type"] = 123
except AssertionError:
    pass
print(h.get("Content-Type"))
# Expected: 'text/html'
# Actual: None

The fix is to validate the new name and value before deleting the old
header.

Linked PRs

Activity

  1. added 3 commits that reference this issue on Sep 26, 2026
  2. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Sep 26, 2026
  3. encukou commented on Sep 29, 2026

    @encukou
    Member

    This behaves as documented:

    Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list.

    I guess it can be changed for the better, but, does this have any real-world impact?

  4. Tony123-tech commented on Oct 4, 2026

    @Tony123-tech
    ContributorAuthor

    I opened a PR (#158226) but don't have a real-world case for the impact, so I closed it. Leaving the issue open in case someone hits it.

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

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions