[New-bugs-announce] [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

Dominik V. report at bugs.python.org
Tue Nov 10 14:35:37 EST 2020


New submission from Dominik V. <dominik.vilsmeier1123 at gmail.com>:

Due to caching of `__getitem__` for generic types, the order of arguments as returned by `get_args` might be different for Union:

```python
>>> from typing import List, Union, get_args
>>> get_args(get_args(List[Union[int, str]])[0])
(<class 'int'>, <class 'str'>)
>>> get_args(get_args(List[Union[str, int]])[0])
(<class 'int'>, <class 'str'>)
```

This is because `List[Union[int, str]] is List[Union[str, int]]`.

I understand that caching is useful to reduce the memory footprint of type hints, so I suggest to update the documentation of `get_args`. At the moment it reads:

> For a typing object of the form X[Y, Z, ...] these functions return X and (Y, Z, ...).

This seems to imply that the returned objects are identical to the ones in the form `X[Y, Z, ...]`. However that's not the case:

```python
>>> U1 = Union[int, str]
>>> U2 = Union[str, int]
>>> get_args(List[U1])[0] is U1
True
>>> get_args(List[U2])[0] is U2
False
```

I'm not so much concerned about the identity, but the fact that a subsequent call to `get_args` on the Union returns a different type seems to be relevant.

So I propose to add the following sentence to the `get_args` docs:

> [...], it gets normalized to the original class.
> If `X` is a `Union`, the order of `(Y, Z, ...)` can be different from the one of the original arguments `[Y, Z, ...]`.

Or alternatively:

> [...], it gets normalized to the original class.
> If `X` is a `Union`, the order of `(Y, Z, ...)` is arbitrary.

The second version is shorter but it's not completely accurate (since the order is actually not arbitrary).

----------
assignee: docs at python
components: Documentation
messages: 380699
nosy: Dominik V., docs at python
priority: normal
severity: normal
status: open
title: 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
type: enhancement
versions: Python 3.9

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


More information about the New-bugs-announce mailing list