Почему Pylance показывает ошибку для одной функции с подсказками типа, но не для другой?Python

Программы на Python
Anonymous
Почему Pylance показывает ошибку для одной функции с подсказками типа, но не для другой?

Сообщение Anonymous »

VSCode Pylance v2023.9.20 со строгой проверкой выдает ошибку типа при первом вызове функции, но не при втором. Единственное отличие состоит в том, что первый аргумент заключен в список.

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

def listTupleFunc(arg: list[tuple[str, tuple[str, ...]]]) -> None:
pass
listTuple = [('x', ('a', 'b'))]
listTupleFunc(listTuple) # Error here

def tupleOnlyFunc(arg: tuple[str, tuple[str, ...]]) -> None:
pass
tupleOnly = ('x', ('a', 'b'))
tupleOnlyFunc(tupleOnly) # OK
И сообщение об ошибке:

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

Argument of type "list[tuple[Literal['x'], tuple[Literal['a'], Literal['b']]]]" cannot be assigned to parameter "arg" of type "list[tuple[str, tuple[str, ...]]]" in function "listTupleFunc"
  "list[tuple[Literal['x'], tuple[Literal['a'], Literal['b']]]]" is incompatible with "list[tuple[str, tuple[str, ...]]]"
    Type parameter "_T@list" is invariant, but "tuple[Literal['x'], tuple[Literal['a'], Literal['b']]]" is not the same as "tuple[str, tuple[str, ...]]"
Если я изменю форматирование некоторые литералов, неожиданно ошибка исчезнет:

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

# These work OK somehow
listTuple = [(f'x', ('a', f'b'))]
listTuple = [(f'x', (f'a', 'b'))]
# But these don't
listTuple = [('x', (f'a', f'b'))]
listTuple = [(f'x', ('a', 'b'))]
Это ошибка в Pylance или я упускаю что-то очевидное? Как избавиться от ошибки?

Подробнее здесь: https://stackoverflow.com/questions/771 ... -the-other

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