Код: Выделить всё
from typing import Type, TypeVar
def printTest(*args):
ret = ltmItemFromIndex(*args)
alt = ltmItemFromIndex_no_match(*args)
test = 'Ok!' if (ret == alt) else 'Fail!'
print(f"args: {args} | ret: {ret} | test: {test}", end="\n\n")
class LineItem:
pass
class ObjectItem:
pass
class RecipeItem:
pass
LTM_ItemType = TypeVar("LTM_ItemType", LineItem, ObjectItem, RecipeItem)
def ltmItemFromIndex(item, itemType: Type[LTM_ItemType]) -> LTM_ItemType | str | None:
match item:
case itemType():
print("case itemType():")
return item
case None:
print("case None:")
return None
case _:
print(error := f"TypeError: {type(item).__name__} instead of {itemType.__name__}!")
return error
def ltmItemFromIndex_no_match(item, itemType: Type[LTM_ItemType]) -> LTM_ItemType | str | None:
if isinstance(item, itemType):
return item
elif item is None:
return None
else:
return f"TypeError: {type(item).__name__} instead of {itemType.__name__}!"
printTest(LineItem(), LineItem)
printTest(None, LineItem)
printTest(32, LineItem)
Однако, когда я запускаю его через Mypy, это повышает эти ошибки:
main.py: error: Expected type in class pattern; found "Type[__main__.LineItem]" [misc]
main.py: error: Expected type in class pattern; found "Type[__main__.ObjectItem]" [misc]
main.py: error: Expected type in class pattern; found "Type[__main__.RecipeItem]" [misc]
https://mypy-play.net/?mypy=latest&pyth ... 835e311f69
>> Я не задумываю, почему Mypy flaging эти ошибки. ltmitemfromindex_no_match () работает нормально, и vscode понимает типы.
Может ли кто -нибудь помочь мне понять, что здесь происходит? < /p>
Подробнее здесь: https://stackoverflow.com/questions/765 ... type-hints