[Python] How can I use mypy's internal type checking functionality?

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a system that lets you use a GUI to write some basic python to use as scripting in an application.

    One of the things it does is let you set an attribute to some value, and I want to see if it can be handled by one of the type handlers that are implemented into the GUI. The native python typing module does not have a way to check if str is a valid type for Optional[str] or if int is valid for Union[float, int, complex] etc...

    However, mypy does this type checking statically and has a function called is_subtype that I think would work great in this case; however, when I call it with python types, I get the exception TypeError: mypy.types.Type object expected; got type, see the code below.

    The mypy internals are pretty complicated, and I can't find a clear path from the python types to what mypy expects internally, is there an easy way to turn native python types into mypy types, or another function I should be using in mypy to check type compatibility at runtime?

    from mypy.subtypes import is_subtype
    is_subtype(float, int)

    Continue reading...

Compartilhe esta Página