Skip to content

Error in TypedDict assignability rule #1973

Closed
@Viicos

Description

@Viicos

The spec says:

First, any TypedDict type is assignable to Mapping[str, object].

Second, a TypedDict type B is assignable to a TypedDict A if and only if both of these conditions are satisfied:

  • For each key in A, B has the corresponding key and the corresponding value type in B is consistent with the value type in A.

  • For each required key in B, the corresponding key is required in A. For each non-required key in B, the corresponding key is not required in A.

However, the following seems to be accepted by type checkers:

from typing import TypedDict


class A(TypedDict):
    a: int

class B(TypedDict):
    a: int
    b: str

def func(a: A): pass

b: B = ...
func(b)  # OK

However, following the second point, any required key in B should be required in A. Or, b is required in B but not required (because not defined) in A.

@JelleZijlstra suggested that the second bullet point should be updated to:

For each required key in A, the corresponding key is required in B. For each non-required key in A, the corresponding key is not required in B.

Should we also say something about extra keys are allowed to be present in B?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions