Рекурсивные типы в Python и трудности с определением типа `type(x)(...)`Python

Программы на Python
Anonymous
Рекурсивные типы в Python и трудности с определением типа `type(x)(...)`

Сообщение Anonymous »

Пытаясь создать рекурсивные типы для аннотирования вложенной структуры данных, я наткнулся на следующее.
Этот код верен согласно mypy:

Код: Выделить всё

IntType = int | list["IntType"] | tuple["IntType", ...]
StrType = str | list["StrType"] | tuple["StrType", ...]

def int2str(x: IntType) -> StrType:
if isinstance(x, list):
return list(int2str(v) for v in x)
if isinstance(x, tuple):
return tuple(int2str(v) for v in x)
return str(x)
Но не этот, который должен быть эквивалентен:

Код: Выделить всё

IntType = int | list["IntType"] | tuple["IntType", ...]
StrType = str | list["StrType"] | tuple["StrType", ...]

def bad_int2str(x: IntType) -> StrType:
if isinstance(x, (list, tuple)):
return type(x)(bad_int2str(v) for v in x)  # error here
return str(x)
Сообщение об ошибке

Код: Выделить всё

line 6: error: Incompatible return value type (
got "list[int | list[IntType] | tuple[IntType, ...]] | tuple[int | list[IntType] | tuple[IntType, ...], ...]",
expected "str | list[StrType] | tuple[StrType, ...]"
)  [return-value]
line 6: error: Generator has incompatible item type
"str | list[StrType] | tuple[StrType, ...]";
expected "int | list[IntType] | tuple[IntType, ...]"  [misc]
Я предполагаю, что mypy может сделать вывод, что type(x) представляет собой либо список, либо кортеж.
Это ограничение mypy или с этим кодом что-то подозрительное?
Если да, то откуда берется ограничение?

Подробнее здесь: https://stackoverflow.com/questions/787 ... e-of-typex

Вернуться в «Python»