list[type, type, ...] ?!

Paul Bryan pbryan at anode.ca
Thu Dec 3 01:37:09 EST 2020


Using the typing.List generic alias, I can only specify a single type.
Example:

>>> typing.List[int]
typing.List[int]

When I try to specify additional types, it fails. Example:

>>> typing.List[int, int]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/typing.py", line 243, in inner
    return func(*args, **kwds)
  File "/usr/lib/python3.9/typing.py", line 775, in __getitem__
    _check_generic(self, params, self._nparams)
  File "/usr/lib/python3.9/typing.py", line 197, in _check_generic
    raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too many parameters for typing.List; actual 2, expected 1

This makes sense to me. An item has one type, and we use Union if we
want variants. What's not making sense to me in Python 3.9: I can use
the built-in generic alias in list in this manner, apparently
successfully:

>>> list[int, int]
list[int, int]

In fact, it appears I can specify an indeterminate number of types. Can
someone explain what this construct means? I suspect this will fail to
be interpreted by type validators, but wonder why it doesn't fail fast
when I express it.

Thanks,

Paul


More information about the Python-list mailing list