Skip to content

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

Open
@gsnedders

Description

@gsnedders

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/[email protected]/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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stubs: false negativeType checkers do not report an error, but should

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions