You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[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'.
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]
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
Activity
Dreamsorcerer commentedon Oct 19, 2020
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.
Dreamsorcerer commentedon Nov 13, 2020
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:
hauntsaninja commentedon Nov 14, 2020
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
Dreamsorcerer commentedon Nov 14, 2020
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.
AlexWaygood commentedon May 3, 2022
I'm closing this issue, as the root cause of the mypy error here is discussed more precisely in #9953