[Python] Python generic type on function getting lost somewhere

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Getting this typing error:

    error: Incompatible types in assignment (expression has type "object", variable has type "A | B") [assignment]


    With this code:

    from dataclasses import dataclass
    from typing import TypeVar, Mapping, reveal_type


    @dataclass
    class A:
    foo: str = "a"

    @dataclass
    class B:
    bar: str = "b"

    lookup_table: Mapping[str, type[A] | type] = {
    "a": A,
    "b": B
    }

    reveal_type(lookup_table) # note: Revealed type is "typing.Mapping[builtins.str, Union[type[simple.A], type[simple.B]]]"
    T = TypeVar("T")

    def load(lookup_table: Mapping[str, type[T]], lookup_key:str) -> T:
    con: type[T] = lookup_table[lookup_key]
    instance: T = con()
    return instance

    example_a: A | B = load(lookup_table, "a") # error: Incompatible types in assignment (expression has type "object", variable has type "A | B")
    print(example_a)


    Edit: Logged a mypy bug here: https://github.com/python/mypy/issues/18265

    Continue reading...

Compartilhe esta Página