Skip to content

TypedDict has no key when checking for key #8887

Closed

Description

@Dreamsorcerer

Minimal test case:

[case testTaggedUnionByKey]
from mypy_extensions import TypedDict
from typing import Union
class A(TypedDict):
    foo: int
class B(TypedDict):
    bar: str
def a(a: Union[A, B]):
    return a["foo"] if "foo" in a else None
[builtins fixtures/tuple.pyi]

The code is checking if the key is present, so this should pass correctly, but instead fails with error: TypedDict "B" has no key 'foo'.

Activity

  1. Dreamsorcerer commented on Oct 19, 2020

    @Dreamsorcerer
    ContributorAuthor

    Coming back to this, it looks like this should be supported by the tagged union pattern documented here:
    https://mypy.readthedocs.io/en/stable/literal_types.html#tagged-unions

    That documentation uses different Literal values on a key, but we should be able to achieve the same thing by testing whether a key exists or not.

  2. Dreamsorcerer commented on Nov 13, 2020

    @Dreamsorcerer
    ContributorAuthor

    Curiously, I can't even get the documented tagged union functionality to work in a test case, or find any code related to the feature. For example, this still fails:

    [case testTaggedUnion]
    from mypy_extensions import TypedDict
    from typing import Union
    from typing_extensions import Literal
    class A(TypedDict):
        foo: Literal[2]
    class B(TypedDict):
        foo: Literal[3]
        bar: str
    def a(a: Union[A, B]):
        return a["bar"] if a["foo"] == 3 else None
    [builtins fixtures/tuple.pyi]
    
  3. hauntsaninja commented on Nov 14, 2020

    @hauntsaninja
    Collaborator

    Your second example passes for me when I run mypy on it as a file (didn't try as a test); maybe you need a different fixture or something. You might be interested in #8151

  4. Dreamsorcerer commented on Nov 14, 2020

    @Dreamsorcerer
    ContributorAuthor

    Thanks for digging that up, must just have been something wrong with the way I was running the test. I'm sure I've used the feature in my code before.

  5. AlexWaygood commented on May 3, 2022

    @AlexWaygood
    Member

    I'm closing this issue, as the root cause of the mypy error here is discussed more precisely in #9953

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions