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
{{ message }}
Repository navigation
@final(TypedDict).get() with unknown key returns object instead of None #12143
Does object | Any not still seem wrong? Going with the spirit of the comment we shouldn't be inferring an Any at all, it seems object | None would make more sense no?
Actually the issue is get("missing_key", foo) cannot infer correct type. #9906 (comment) Jukka explained this before.
I think the real issue why this can't be inferred is the allowance of inheritance. I think there was a conversation about this elsewhere, but my example can't work, as you could create a subclass with any other type like:
class A(TypedDict): ...
class B(A):
foo: str
b: B = {"foo": "bar"}
a: A = b
reveal_type(a.get("foo", None))
In the future, it might be possible to support my example using final types:
@final
class A(TypedDict): ...
At that point, there is no reason it can't be inferred. The key is a literal and it can be checked what type it should return (or no type if not present).
Just to confirm for more visibility: @final decorator on TypedDicts is now soft-deprecated (and is only supported on the best effort basis), for all relevant use cases, please use PEP 728 closed=True.
Activity
97littleleaf11 commentedon Mar 19, 2022
Actually the issue is
get("missing_key", foo)cannot infer correct type. #9906 (comment) Jukka explained this before.jhance commentedon Mar 19, 2022
Does
object | Anynot still seem wrong? Going with the spirit of the comment we shouldn't be inferring anAnyat all, it seemsobject | Nonewould make more sense no?97littleleaf11 commentedon Mar 19, 2022
I can only get
objecton master branchDreamsorcerer commentedon Mar 19, 2022
I think the real issue why this can't be inferred is the allowance of inheritance. I think there was a conversation about this elsewhere, but my example can't work, as you could create a subclass with any other type like:
In the future, it might be possible to support my example using final types:
At that point, there is no reason it can't be inferred. The key is a literal and it can be checked what type it should return (or no type if not present).
[-]Empty TypedDict returns object[/-][+]@final(TypedDict).get() with unknown key returns object instead of None[/+]roganov commentedon Apr 2, 2024
Another example of the issue:
The inferred type should be
list[Node], notbuiltins.object.ilevkivskyi commentedon Jun 2, 2026
Just to confirm for more visibility:
@finaldecorator on TypedDicts is now soft-deprecated (and is only supported on the best effort basis), for all relevant use cases, please use PEP 728closed=True.Implement support for closed TypedDicts (PEP 728) (python#21382)