Skip to content

MutableMapping cannot be instantiated from Headers #2989

@progval

Description

@progval

This bit of code from requests passes an instance of werkzeug's Headers to collections.abc.MutableMapping.update(): https://github.com/psf/requests/blob/main/src/requests/adapters.py#L375

Essentially, it does something like this:

>>> from werkzeug.datastructures.headers import Headers
>>> from requests.structures import CaseInsensitiveDict
/usr/lib/python3/dist-packages/requests/__init__.py:109: RequestsDependencyWarning: urllib3 (2.2.3) or chardet (5.2.0)/charset_normalizer (3.0.1) doesn't match a supported version!
  warnings.warn(
>>> headers = Headers([('Content-Type', 'text/plain'), ('Content-Length', '1')])
>>> CaseInsensitiveDict(headers)
{'Content-Type': 'text/plain', 'Content-Length': '1'}

but it does not work since Werkzeug 3.1.0:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/requests/structures.py", line 44, in __init__
    self.update(data, **kwargs)
  File "<frozen _collections_abc>", line 949, in update
  File "/home/dev/.local/lib/python3.11/site-packages/werkzeug/datastructures/headers.py", line 88, in __getitem__
    return self.__class__(self._list[key])
                          ~~~~~~~~~~^^^^^
TypeError: list indices must be integers or slices, not tuple

This is because CaseInsensitiveDict calls the update method of collections.abc.MutableMapping, which calls iter() on the header object to get what it assumes is an iterator of keys (but for Headers it's an iterator of (key, value) pairs), then calls getitem for each "key".

Environment:

  • Python version: 3.11
  • Werkzeug version: 3.1.0 or 3.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions