-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document TypedDict 'in' narrowing #15695
Comments
I was the one who originally suggested that this type guard pattern would be safe if the The problem is that Faced with this realization, I just changed pyright to no longer require This type guard pattern admittedly opens a small hole in the type system because it's possible that the object at runtime has a key with the name specified in the type guard but still matches the structural definition. In practice, this rarely if ever happens. I verified that TypeScript (whose type system is exclusively structural) supports this same type guard and exhibits the same theoretical hole, but the TypeScript maintainers felt that it was a reasonable and practical tradeoff. I agree with that assessment, so I'm OK supporting this type guard pattern in pyright. Assuming you agree with my logic, you may want to change mypy's behavior and remove the requirement that the TypedDict is marked |
Can you clarify with an example? |
In this issue, you mentioned that class BookBasedOnMovieResponse(BookResponse):
movie: Movie You're correct that this definition would not be possible if class BookBasedOnMovieResponse(TypedDict):
book: Book
movie: Movie The fact that the first definition "derives from" |
Created #15697. We should still document the narrowing itself as an alternative to tagged unions. |
I guess a temptation to be strict comes from the fact that PEP 589 tries vaguely to be strict during construction, in a way that is not really structural:
Even though:
I do think the argument for allowing unsoundness here is stronger in TypeScript than it is in Python. But the ways I've seen people use TypedDict don't seem to be really wanting strong guarantees and IIRC we've already made some unsound concessions around TypedDict creation, so I guess I'm fine with it |
FWIW from typing import TypedDict
class A(TypedDict):
a: str
class B(A):
b: int
x: A = {"a": "asdf", "b": 5} # error is TypeScript's excess property check. |
In particular, document the need for@final
in order for it to work.The text was updated successfully, but these errors were encountered: