python / python/typeshed

json.dump/dumps shouldn't allow `Any` when `default` is None

Open
#13,781 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stubs: false negative
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

When default is None, we know what types are serialisable.

Thus,

import json
import types
import typing

def x(data: typing.Mapping[str, str]) -> str:
    return json.dumps(data)

def y():
    return json.dumps(types.MappingProxyType({}))

Shouldn't type-check.

Running this fails with:

File /opt/homebrew/Cellar/python@3.13/3.13.2/Frameworks/Python.framework/Versions/3.13/lib/python3.13/json/encoder.py:180, in JSONEncoder.default(self, o)
    161 def default(self, o):
    162     """Implement this method in a subclass such that it returns
    163     a serializable object for ``o``, or calls the base implementation
    164     (to raise a ``TypeError``).
   (...)    178 
    179     """
--> 180     raise TypeError(f'Object of type {o.__class__.__name__} '
    181                     f'is not JSON serializable')

TypeError: Object of type mappingproxy is not JSON serializable

Type-checking JSONEncoder itself would be much harder, but the more-commonly-used functions should be doable via overloads.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the json.dump and json.dumps stubs and inspect how their overloads handle the default argument. Check the examples in the issue against the resulting types; done means calls without a default reject unsupported inputs while calls with a default remain appropriately typed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.