-
-
Notifications
You must be signed in to change notification settings - Fork 3k
[PEP 747] Recognize TypeForm[T] type and values (#9773) #19596
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
base: master
Are you sure you want to change the base?
Conversation
User must opt-in to use TypeForm with --enable-incomplete-feature=TypeForm
In particular:
* Recognize TypeForm[T] as a kind of type that can be used in a type expression
* Recognize a type expression literal as a TypeForm value in:
- assignments
- function calls
- return statements
* Define the following relationships between TypeForm values:
- is_subtype
- join_types
- meet_types
* Recognize the TypeForm(...) expression
* Alter isinstance(typx, type) to narrow TypeForm[T] to Type[T]
In particular:
- Adjust error messages to use lowercased type names, which is now the default
- Adjust error message to align with upstream stub changes
- Fix multiple definition of TypeForm in typing_extensions.pyi, because definition was added upstream
- Fix TypeType equality definition to recognize type forms
- Fixes test: $ pytest -q -k testTypeFormToTypeAssignability
…nied note to standalone error
…te to a new context manager
...at the most-targeted location
Specific warning:
* SyntaxWarning: invalid escape sequence '\('
…nd the --dump-build-stats option
...in SemanticAnalyzer.try_parse_as_type_expression()
…d by TA.try_parse_as_type_expression()
…n checking open source code
for more information, see https://pre-commit.ci
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
for more information, see https://pre-commit.ci
This comment has been minimized.
This comment has been minimized.
|
I fixed all the "only in CI" check issues so this PR is now actually ready for review. |
|
@JukkaL Did you want to look at this latest PR draft yourself, or recommend a review from any of the other mypy maintainers? |
|
I can have a look. Sorry for the delay, this is a big PR and I need to block some time to review this properly. |
|
Sometime between 2-6 weeks from now I'm expecting to become unavailable for a few months due to increased family commitments. If it's possible to get feedback on this PR before then, it will be able to be merged in a timely fashion and mypy will gain TypeForm support in 2025. |
|
I have a limited amount of time now each day to review PR feedback, which I expect to continue having over the next 2 weeks. @JukkaL if you find a block of time to review during that window, I should be able to respond to you. |
|
I have blocked time in my calendar to review the PR next week. Again, apologies for the slow response. |
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.
This is looking good now, thank you for all the updates! I measured performance and it's looking good -- I couldn't measure a difference compared to master. Left a few comments that would be good to fix before merging (plus there are a few merge conflicts).
The following things are optional for now -- it's fine to merge the PR after the comments have been addressed and create a follow-up issue (or issues) about these.
Callable[[], int]isn't accepted as a TypeForm, unless I put in in a string literal.Literal[1]is similar -- it isn't accepted.- It would be good to have tests for other kinds of types that are missing coverage (fixed-length tuple,
type[int]as a type form, TypedDict type, NoReturn). - What should happen if a type variable type such as
Tis used as a TypeForm -- is it supposed to work? Right now it seems to be rejected. - It would be good to have one or two incremental and daemon mode tests.
|
Thanks for taking a look @JukkaL ! I'll get started on making revisions over the next few days, with the goal of having a clean squashable branch ready to merge. |
|
Note that I will be on vacation from Oct 22, but I'll review your changes once I'm back. |
This comment has been minimized.
This comment has been minimized.
…Form when checking open source code" This reverts commit d8c59f5.
This comment has been minimized.
This comment has been minimized.
|
Update: I've pushed fixes to every PR comment. I'm currently looking at a few of the bonus items mentioned by Jukka, since I'm thinking of fixing a few of them as part of this PR. In particular the inability to assign I'm going to see if I can find time within the next 3 days to fix that last issue as part of this PR. The remaining bullets I'm looking at filing as post-merge GitHub issues to investigate/fix. |
for more information, see https://pre-commit.ci
…ional, Union, Callable
This comment has been minimized.
This comment has been minimized.
… for Python 3.9 - 3.11
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
These issues are now fixed, by commit fadc994:
Indeed using a type variable type like However probably type variables like
I'm not familar with either incremental or daemon mode tests presently. I'll address this in a followup issue. (Edit 2: Issue created) 👈(♯2) @JukkaL I think this branch is ready to merge. |
(This PR replaces an earlier draft of the same feature: #18690 )
Feedback from @JukkaL integrated since the last PR, by commit title:
Feedback NOT integrated, with rationale:
Type[...], which I can fix in a separate PR.TypeForm(...)in value contexts as a regular function likeCallable[[TypeForm[T]], TypeForm[T]]rather than as a special expression node (TypeFormExpr).TypeForm(...). See case 4 of testTypeFormExpression in check-typeform.testThere is one NOMERGE commit temporarily in this PR so that mypy_primer gives more insightful CI output:
There is one commit unrelated to the core function of this PR that could be split to a separate PR:
Closes #9773
(Most of the following description is copied from the original PR, except for the text in bold)
Implements the TypeForm PEP 747, as an opt-in feature enabled by the CLI flag
--enable-incomplete-feature=TypeForm.Implementation approach:
The
TypeForm[T]is represented as a type using the existingTypeTypeclass, with anis_type_form=Trueconstructor parameter.Type[C]continues to be represented usingTypeType, but withis_type_form=False(the default).Recognizing a type expression literal such as
int | strrequires parsing anExpressionas a type expression. Only the SemanticAnalyzer pass has the ability to parse arbitrary type expressions (including stringified annotations), usingSemanticAnalyzer.expr_to_analyzed_type(). (I've extended theTypeCheckerpass to parse all kinds of type expressions except stringified annotations, using the newTypeCheckerAsSemanticAnalyzeradapter.)Therefore during the SemanticAnalyzer pass, at certain syntactic locations (i.e. assignment r-values, callable arguments, returned expressions), the analyzer tries to parse the
Expressionit is looking at usingtry_parse_as_type_expression()- a new function - and stores the result (aType) in{IndexExpr, OpExpr, StrExpr}.as_type- a new attribute.During the later TypeChecker pass, when looking at an
Expressionto determine its type, if the expression is in a type context that expects some kind ofTypeForm[...]and the expression was successfully parsed as a type expression by the earlier SemanticAnalyzer pass (or can be parsed as a type expression immediately during the type checker pass), the expression will be given the typeTypeForm[expr.as_type]rather than using the regular type inference rules for a value expression.Key relationships between
TypeForm[T],Type[C], andobjecttypes are defined in the visitors poweringis_subtype,join_types, andmeet_types.The
TypeForm(T)expression is recognized as aTypeFormExprand has the return typeTypeForm[T].The new test suite in
check-typeform.testis a good reference to the expected behaviors for operations that interact withTypeFormin some way.Controversial parts of this PR, in @davidfstr 's opinion:
Type form literals containing stringified annotations are only recognized in certain syntactic locations (and not ALL possible locations). Namely they are recognized as (1) assignment r-values, (2) callable expression arguments, and (3) as returned expressions, but nowhere else. For example they aren't recognized in expressions like
dict_with_typx_keys[int | str]. Attempting to use stringified annotations in other locations will emit a MAYBE_UNRECOGNIZED_STR_TYPEFORM error.The existing
TypeTypeclass is now used to represent BOTH theType[T]andTypeForm[T]types, rather than introducing a distinct subclass ofTypeto represent theTypeForm[T]type. This was done to simplify logic that manipulates bothType[T]andTypeForm[T]values, since they are both manipulated in very similar ways.The "normalized" form of
TypeForm[X | Y]- as returned byTypeType.make_normalized()- is justTypeForm[X | Y]rather thanTypeForm[X] | TypeForm[Y], differing from the normalization behavior ofType[X | Y].