Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
gsnedders opened this issue Apr 3, 2025 · 2 comments
Open

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

gsnedders opened this issue Apr 3, 2025 · 2 comments
Labels
stubs: false negative Type checkers do not report an error, but should

Comments

@gsnedders
Copy link

gsnedders commented Apr 3, 2025

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.

@srittau srittau added the stubs: false negative Type checkers do not report an error, but should label Apr 3, 2025
@srittau
Copy link
Collaborator

srittau commented Apr 3, 2025

Makes sense. Any improvements are welcome!

@max-muoto
Copy link
Contributor

Put up a PR here! #13960

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false negative Type checkers do not report an error, but should
Projects
None yet
Development

No branches or pull requests

3 participants