illuminato
illuminato

Reputation: 1257

Python annotation's type for nested list with undefined nested list depth

Type of [[1, 2, 3], 3, [2, 4], 5] is list[list[int] | int]. But what type nested list would have if it has undefined depth e.g. [[[1, 2]], 2, [1, [3, [3]]]], 3, [2, [2]]]?

Upvotes: 2

Views: 855

Answers (2)

schachmett
schachmett

Reputation: 94

Now that PEP 695 was accepted, you can do the following in Python 3.12:

type NestedList = list[int | NestedList]

Note that you can even drop the " around NestedList because it is no longer a forward reference.

You can even make it a generic type so that you can easily get a nested list of, for example, strings instead of integers:

type NestedList[T] = list[T | NestedList[T]]
nest_string_list: NestedList[str] = []

mypy accepts this since version 1.11 if you use the option enable_incomplete_feature = ["NewGenericSyntax"]. I presume that it will be fully supported in the next version.

Upvotes: 2

Vladimir Fokow
Vladimir Fokow

Reputation: 3883

You can define a recursive type alias:

T: TypeAlias = list[Union[int, 'T']]

Upvotes: 4

Related Questions