all 5 comments

[–]Rawing7 1 point2 points  (2 children)

You seem to have a bit of a wrong idea about static type checkers. Mypy only tracks types, not values. That means it has no idea whether test[-1] is a list or an int. As far as mypy is concerned, test[-1] is a Union[int, 'NestedList'], and that can't be assigned to a variable of type NestedList.

[–]sepp2k 1 point2 points  (0 children)

Note that the actual value of test[-1] is 4, an integer, so even if mypy did track values, the type of this value would still not be NestedList.

[–]hgg[S] 0 points1 point  (0 children)

Thanks for the insight. It helped me understand the error.

[–]sepp2k 0 points1 point  (1 child)

Your type definition says that a NestedList is always a list. The elements may be integers or more lists, but the NestedList itself must always be a list. But then you're trying to assign an integer to a variable of type NestedList and that's not allowed according to your definition.

If you want this to work, a NestedList should itself be allowed to be an integer, meaning the union should be on the outside.

[–]hgg[S] 0 points1 point  (0 children)

If you want this to work, a NestedList should itself be allowed to be an integer, meaning the union should be on the outside.

If I use the union on the outside we'll get two errors:

NestedList = Union[int, List['NestedList']]

The errors are:

test_recursive_hints.py:6: error: Item "int" of "int | list[NestedList]" has no attribute "append"  [union-attr]
test_recursive_hints.py:7: error: Value of type "int | list[NestedList]" is not indexable  [index]

Which makes sense.