Reputation: 6299
I'm asking here before opening an issue because I'm not sure if this is expected behavior. My felling tells me that it has to do with runtime checking but I'm not sure,
I have this MVE
from typing import Optional
from typing_extensions import TypedDict
D = TypedDict("D", {"bar": Optional[str]})
def foo() -> None:
a: D = {"bar": ""}
a.get("bar", "").startswith("bar")
mypy will complain:
Item "None" of "Optional[str]" has no attribute "startswith"
Now is pretty obvious that since second argument of get is an string, the return has .startswith, but still the error. I'm using # type:ignore
on this, is there any other way?
Upvotes: 0
Views: 1346
Reputation: 225174
Optional[T]
represents a T
or None
, so a: D = {"bar": None}
would typecheck and that’s why a.get("bar", "").startswith("bar")
can’t. If you’re okay with every key in the TypedDict
being optional, there’s total=False
:
D = TypedDict("D", {"bar": str}, total=False)
Upvotes: 2