-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Use TypeIs for is_typeddict
#12039
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
Use TypeIs for is_typeddict
#12039
Conversation
This comment has been minimized.
This comment has been minimized.
The only change from mypy primer fixes a false positive in Pydantic: if is_typeddict(tp):
return tp.__orig_bases__ # type: ignore (This is valid, and will type check correctly now, on 3.12+) |
The mypy primer hit is saying that the |
Edit: One reason why that might be is because |
# __orig_bases__ sometimes exists on <3.12, but not consistently,
# so we only add it to the stub on 3.12+
if sys.version_info >= (3, 12):
__orig_bases__: ClassVar[tuple[Any, ...]] |
Mypy primer results are a diff. If a line is coloured in red with a minus sign at the beginning, it means that mypy emitted that message with the typeshed main branch, but no longer emits that message with the PR branch. |
I see, makes sense! |
But yeah, as you say, the new error seems like a true positive rather than a false positive — it shows mypy applying type narrowing correctly! |
Could you apply the same change to |
Will do! |
|
Diff from mypy_primer, showing the effect of this PR on open source code: pydantic (https://github.com/samuelcolvin/pydantic)
- pydantic/_internal/_decorators.py:285: error: Unused "type: ignore" comment [unused-ignore]
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Advantages of doing this:
- It allows type checkers to apply type narrowing when they see
is_typeddict
being used, which means that users can safely access class-level attributes such as__required_keys__
and__optional_keys__
on TypedDict classes.
Disadvantages of doing this:
- It's a bit weird for type checkers to narrow to a fictional type.
typing._TypedDict
doesn't actually ever appear in a TypedDict class's mro; it's a class factory rather than a base class:>>> from typing import TypedDict >>> class Foo(TypedDict): pass ... >>> Foo.__mro__ (<class '__main__.Foo'>, <class 'dict'>, <class 'object'>)
- The only real-world case where mypy_primer highlights this making a difference regards
__orig_bases__
. We already have a type-safe helper function for regarding that attribute (types.get_original_bases
, backported astyping_extensions.get_original_bases
), so I'm not sure I see that as a convincing use case.
Overall, I think I'm -0 on this. But curious about what other maintainers think.
I would oppose adding this. |
Use
TypeIs
foris_typeddict
, which will allow code like this to be type-checked properly, similarly to: #11929: