Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type annotation for nested lists

I'd like to annotate my return type which happens to be a list containing lists of integers. Is this annotation: List[List[int]] okay? Here's exact example of my return type:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 331
jav321 Avatar asked Apr 10 '18 22:04

jav321


1 Answers

Yes, List[List[int]] is the correct type.

As a side note, whenever you're unsure of the type, you can define that variable and use the Mypy reveal_type method to have it guess the correct type. For example:

> cat foo.py
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
reveal_type(a)

> mypy foo.py
1.py:2: note: Revealed type is 'builtins.list[builtins.list*[builtins.int]]'

which tells you that the type of a is List[List[int]]. Note that reveal_type is not a valid function; it's rather a special syntax built into Mypy. If you try to run foo.py in Python, it'll throw a NameError.

For more information, consider reading the Mypy docs.

like image 61
Zecong Hu Avatar answered Sep 28 '22 05:09

Zecong Hu