简体   繁体   中英

What type hints should be used for recursively nested objects in Python?

For instance, what is a good syntax for a type like that:

list[int | list[int | ...]]

Basically, for a list of int s that could be of any (strictly positive) dimension.

I was able to find a solution, by following the logic in this answer (as suggested by @juanpa.arrivillaga), and using a forward reference.

The type ( T ) for an n-dimensional list of int s could be noted as:

import typing
T = list[typing.Union[int, 'T']]

NB: whereas typing.Union(T1, T2) can also be written as T1 | T2 T1 | T2 , it doesn't work in the context of this answer (as of Python 3.9):

>>> T = list[int | 'T']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'type' and 'str'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM