Skip to content

TypedDict of X and Y not compatible with Mapping[str, Union[X, Y]] #8994

Description

@JosiahKane

Feature request: track the common type in a TypedDict.

It has been established (#4976 ) that TypedDict is compatible with Mapping[str, Any] (although not with Dict) because it hides mutating operations. However, it is not compatible with any more specific Mapping Types, even though it clearly has all the information needed to identify the possible value types.

class T(TypedDict):
    a: int
    b: int

def foo(x: Mapping[str, int]):
    ...

def bar(y: Mapping[str, str]):
    ...

def qux(z: Mapping[str, Any]):
    ...

s = {"a": 5, "b": 3}
foo(s)
bar(s)
qux(s)
t: T = {"a": 5, "b": 3}
foo(t)
bar(t)
qux(t)

Expected behaviour:
bar(s) and bar(t) should fail.
qux(s) and qux(t) should pass.
foo(s) and foo(t) should pass.

Observed behaviour (MyPy 0.780 on Windows):
bar(s) and bar(t) fail.
qux(s) and qux(t) pass.
foo(s) passes but foo(t) fails.

A TypedDict can safely be considered a Mapping from str to the Union of the types of the presented entries. A significant implication of this is that it is safe to iterate over a TypedDict and use information common to all represented types.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions