
Am 21.09.20 um 16:28 schrieb Zac Hatfield Dodds:
Rather than defining a new Any type, this seems to me rather like a TypeVar with what the Mypy docs call value restriction (not a bound). For example:
* ip_address() can return either an IPv4Address or an IPv6Address, depending on the input string. * urlopen() can return either an HTTPResponse or an addinfourl.
def ip_address(s: str) -> TypeVar("address", IPv4Address, IPv6Address): ... # and similarly for urlopen()
I think this would also require new logic from typecheckers because I don't believe you can currently have a return typevar without an argument typevar, but the spelling makes sense to me and narrowing should be as obvious as it ever is between typecheckers.
I don't think that TypeVars are a good fit. As you point out, TypeVars only make sense if there are at least two instances of it in a definition. They have a completely different purpose (being variables) than what AnyOf is supposed to do.
* json.loads() et al. can return a selection of types, depending on the input.
JSON is really a case for recursive types - "we usually omit the base case" isn't much worse to me than "one or more layers in it's just Any".
It would definitely benefit greatly from recursive types, although I think this is a bit of an orthogonal issue. - Sebastian