[issue42317] Docs of `typing.get_args`: Mention that due to caching of typing generics the order of arguments for Unions can be different from the one of the returned tuple

Ken Jin report at bugs.python.org
Wed Nov 11 09:01:02 EST 2020


Ken Jin <kenjin4096 at gmail.com> added the comment:

You're right, currently this happens for 2 reasons:

1. _SpecialGenericAlias (used by List), caches its __getitem__. (As you already pointed out :) )

2. _UnionGenericAlias (Union)'s __hash__ is `hash(frozenset(self.__args__))`. i.e. Unions with different args orders but same unique args produce the same hash result. Causing the same cache hit.

I find it mildly sad however that:

>>> get_args(Union[int, str])
[int, str]

>>> get_args(Union[str, int])
[str, int]

Which is slightly inconsistent with its behavior when nested in List. I don't think there's an easy way to fix this without breaking the cache (and also it makes sense that Unions' args aren't order dependent). So I'm all for updating the docs with your addition (slightly edited):

> If `X` is a `Union`, the order of `(Y, Z, ...)` may be different from the order of the original arguments `[Y, Z, ...]`.

----------
nosy: +gvanrossum, kj, levkivskyi
versions: +Python 3.10

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42317>
_______________________________________


More information about the Python-bugs-list mailing list