[Python] Mypy error with valid Python 3.10 code involving pattern matching and type hints

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code snippet in Python 3.10/3.11 and I'm trying to match on the type passed as argument, but mypy doesn't like it

    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)


    The code runs without any issues and can be tested here: https://onlinegdb.com/qTcB52ZH5 However, when I run it through mypy, it raises these errors:

    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&python=3.10&gist=145441c5574c2bd1bc16a1835e311f69

    I'm confused about why mypy is flagging these errors when the code seems to be correct.
    Also, ltmItemFromIndex_no_match() runs fine and VSCode understands the types.
    Can someone help me understand what's going on here?

    Continue reading...

Compartilhe esta Página