Skip to content

Generic type falling back to object - possibly related to type[ Union ]? #18265

Closed
@JakeSummers

Description

@JakeSummers

Bug Report

The following code produces a type error but it shouldn't.

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 on mypy Playground)
  • Mypy command-line flags: None.
  • Python version used: 3.11, 3.12, 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions