Closed
Description
Bug Report
The following code produces a type error but it shouldn't.
- Gist URL: https://gist.github.com/mypy-play/b4d24f9b14f909a7d6550ff738cd4fb1
- Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=b4d24f9b14f909a7d6550ff738cd4fb1
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[B]] = {
"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)
Error:
error: Incompatible types in assignment (expression has type "object", variable has type "A | B") [assignment]
Your Environment
- Mypy version used:
1.13.0
(latest onmypy Playground
) - Mypy command-line flags: None.
- Python version used: 3.11, 3.12, 3.13