[Python-ideas] Proposal: Use mypy syntax for function annotations

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Aug 14 08:48:07 CEST 2014


Andrew Barnert wrote:
> If you go with a single JSONThing type that represents an object, array, 
> number, bool, string, or null, then it can't have a standard mapping 
> interface, because it also needs to have a standard sequence interface,

I didn't mean that. The most Pythonic way would probably be to
have something like

JSONThing = Union(JSONDict, JSONList, Int, Float, Str, Bool)
JSONDict = Mapping[str, JSONThing]
JSONList = Sequence[JSONThing]

If you're concerned about type safety, at some point you
need to introspect on what you've got to figure out what
to do with it. This is inevitable, since a JSON object
is inherently a dynamically-typed thing. This is true
even in Haskell, you just don't notice it so much because
you do it with pattern matching.

> The only 
> possibility is a union of all the various types mentioned above, and 
> such a union type has no interface at all. It's only useful if people 
> subvert the type safety by casting.

I don't know what mypy does with union types, but if I were
designing a type system like this I would say that, e.g. if
i is know to be of type Int and d of type JSONDict, then

    i = d['foo']

should be allowed, on the grounds that the return value
*could* be an Int, with a run-time type check to make sure
that it actually is. An implicit cast, in other words.

As long as mypy is just a linter it's obviously not in
a position to insert the runtime check, but it could be
argued that it should allow the assignment anyway,
since Python will end up raising a TypeError at some
point if it's wrong.

I've forgotten what the original point of all this was.
If the point was that there's no benefit in trying to
make JSON type-safe in Python, and you should just leave
it all dynamically typed, maybe you're right.

-- 
Greg


More information about the Python-ideas mailing list