My solution to typing json.loads

In response to Stdlib json.load[s]() return type

This may shock you, but this is because the two are incompatible types :face_with_tongue:. Specifically, you’re trying to assign to something with a type of dictionary with string keys, and the JSON value could be (for instance) an int!

For instance, the following modification works fine:

dct: dict[str, Any] = {"": data}

You can also cast(dict, data)

You actually can do this — although, the type has to be given as a normal argument. (Also, it doesn’t assign a type to a variable, just to a return type.) I have a tiny utility function that does something along these lines and raises an exception if the type isn’t correct. This allows the rest of the program (and type checker) to proceed along sure in the knowledge that it has the right type of thing from that function’s return. Another possibility for the implementating function would be casting whatever’s in there to that type — I’m not sure what the point would be, however, since that is effectively what returning Any does, too. Or a cast at the calling site.

I just think those things are interesting. The actual question of the thread is already answered :slightly_smiling_face:

This was actually a reply to a different musing in the same thread, which context seems to have been lost by the topic move (along with, for some reason, my ability to edit the above post, to add the context back in — not that I’m perturbed by this to any significant degree; just explaining) https://discuss.python.org/t/stdlib-json-load-s-return-type/67772/7o

1 Like