Skip to content

RequestsCookieJar shouldn't inherit from MutableMapping #7228

@shelvacu

Description

@shelvacu

RequestsCookieJar currently inherits from both CookieJar and MutableMapping, but these classes are incompatible. CookieJar.__iter__ iterates over Cookies, whereas MutableMapping expects __iter__ to iterate over the key type (str).

Expected Result

RequestsCookieJar does not inherit from MutableMapping

(or the values produced by __iter__ can be passed to __getitem__)

Actual Result

__iter__ produces Cookies, and __getitem__ raises KeyError if any non-str is passed

Reproduction Steps

from collections.abc import MutableMapping
import requests

# this function should work with any object that correctly implements MutableMapping
def example(some_obj):
    print(f"example(some_obj:{type(some_obj).__name__})")
    if isinstance(some_obj, MutableMapping):
        for key in some_obj:
            print(f"some_obj[{key!r}] = {some_obj[key]!r}")

example("")
example({"foo": 1})

cookie_jar = requests.cookies.RequestsCookieJar()
cookie_jar["foo"] = "1"
example(cookie_jar) # raises KeyError

System Information

$ python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.4.3"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.11"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.13.11"
  },
  "platform": {
    "release": "6.12.70",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.32.5"
  },
  "system_ssl": {
    "version": "30600010"
  },
  "urllib3": {
    "version": "2.5.0"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}

but this should apply to any version since 4d6871d

Additional context

This is particularly a problem for correctly typing RequestsCookieJar, which is how I ran into this. See python/typeshed#15457

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions