[Python] Computed from constant expressions type hints

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

  1. Stack

    Stack Membro Participativo

    I would like to define class properties in Python using a dictionary to map property names to their corresponding types. However, when using a naive approach, Pylance reports an error Illegal type annotation: variable not allowed unless it is a type alias. Here is an example of what I am trying to accomplish:

    from enum import Enum, auto

    class Keys(Enum):
    Integer = auto()
    String = auto()

    types = {Keys.Integer: int, Keys.String: str}

    class MyClass:
    int_property: types[Keys.Integer] # Error is reported here
    str_property: types[Keys.String] # Error is reported here


    Is there a way to achieve this kind of structure while still getting correct type hints from Pylance?

    Continue reading...

Compartilhe esta Página