#python #type-hinting #mypy
#python #подсказка типа #mypy
Вопрос:
У меня есть функция python, которая выглядит следующим образом:
from typing import Tuple
def test() -> Tuple[int]:
o: Tuple[int] = ()
for i in range(2):
o =(i,)
return o
Оценка этого с помощью mypy возвращает ошибки
error: Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[int]")
error: Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[int]")
Присвоение кортежу и возвращаемому значению типа Tuple без спецификации int решает эту проблему. Я хотел бы также указать содержимое кортежа. Как я могу этого добиться?
Ответ №1:
# For tuples of variable size, we use one type and ellipsis
x: tuple[int, ...] = (1, 2, 3) # Python 3.9
x: Tuple[int, ...] = (1, 2, 3)
От:
Ответ №2:
Что касается подсказок типа, Tuple
не похоже List
.
Tuple[int]
означает «a tuple
из 1 int
»
Tuple[int, int]
означает «a tuple
из 2 int
s»
List[int]
означает «a list
из int
s»