Skip to content

Inline annotations in 2.34.0 cause mypy error for Request json payloads #7434

@JamMarHer

Description

@JamMarHer

requests version 2.34.0 added inline type annotations. This is causing some issues with mypy, specifically building a Request with a json argument.

The MR (#7272) that introduced the feature notes that mypy support is not currently a goal, but I think it's worth sharing this issue.

Expected Result

Passing a JSON-compatible dictionary to the json argument of requests.Request should type-check successfully.

For example, a value typed as:

dict[str, None | bool | int | float | str]

or the narrower:

dict[str, str]

should be accepted as a valid JSON payload.

Actual Result

mypy reports an incompatible argument type error when a dictionary is passed to the json argument.

Reproduction Steps

Create a file named test.py:

from requests import Request

payload: dict[str, str] = {"test": "test"}

request = Request(json=payload)

Then run mypy (used 2.1.0) against the python code:

python -m mypy test.py
test.py:5: error: Argument "json" to "Request" has incompatible type "dict[str, str]"; expected "JsonType"  [arg-type]
test.py:5: note: "dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:5: note: Consider using "Mapping" instead, which is covariant in the value type
Found 1 error in 1 file (checked 1 source file)

System Information

$ python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.4.7"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.14"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.13.13"
  },
  "platform": {
    "release": "24.6.0",
    "system": "Darwin"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.34.0"
  },
  "system_ssl": {
    "version": "30600020"
  },
  "urllib3": {
    "version": "2.7.0"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}

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