Home > Enterprise >  Correct typing for list of ints
Correct typing for list of ints

Time:09-16

Consider the following code in file x.py

from typing import List, Optional

my_list: List[Optional[int]] = list()
for i in range(7):
    my_list.append(i)
my_list = sorted(my_list)
if (len(my_list) > 0):
    my_list.append(None)
# do something with my_list

The command mypy x.py gives the following error:

x.py:6: error: Value of type variable "SupportsRichComparisonT" of "sorted" cannot be "Optional[int]"

So I changed x.py to the following:

from typing import List

my_list: List[int] = list()
for i in range(7):
    my_list.append(i)
my_list = sorted(my_list)
if (len(my_list) > 0):
    my_list.append(None)
# do something with my_list

But now mypy x.py outputs

x.py:8: error: Argument 1 to "append" of "list" has incompatible type "None"; expected "int"

So how do I annotate the code correctly for mypy to not complain (of course both versions behave exactly the same during runtime and work as expected)?

The "None"-element at the end of the list is needed in the "do something"-part of the script (which is not relevant for the problem and therefore not shown here)

CodePudding user response:

Instead of assigning the sorted list back to the original variable my_list, assign it to a new variable which mypy will allow to hold different types.

my_list: List[int] = list()
for i in range(7):
    my_list.append(i)
# change here
sorted_list: List[Any] = sorted(my_list)
if len(sorted_list) > 0:
    sorted_list.append(None)

CodePudding user response:

Based on crunker99's answer that correctly pointed out the new list I was able to come up with this code that satisfies mypy:

from typing import List, Optional

my_list: List[int] = list()
for i in range(7):
    my_list.append(i)
my_sorted_list: List[Optional[int]] = list(sorted(my_list))
if (len(my_sorted_list) > 0):
    my_sorted_list.append(None)
# do something with my_sorted_list
  • Related