python: add more precise typehints for immutable structs#3321
Merged
Jens-G merged 1 commit intoapache:masterfrom Feb 25, 2026
Merged
python: add more precise typehints for immutable structs#3321Jens-G merged 1 commit intoapache:masterfrom
Jens-G merged 1 commit intoapache:masterfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This change extends the type-hinted codegen to work more nicely with frozen structs. We directly use the same logic in
member_hintwhich adds type annotations to the__init__to provide class-level annotations.Using the tutorial structs:
Before
After
Diff
Why
Because we use
super(...).__setattr__in frozen structs to initially set the relevant attributes, typecheckers can't see or understand what attributes exist on the struct when typechecking.We the below examples:
typlaygroundNote:
tycurrently has the worst behaviour because it does not understand attributes in__slots__yet. I suspect behaviour would be in line after astral-sh/ruff#20996pyrightplaygroundNote: here, pyright doesn't throw an error, but if you hove over
e.errorCodeyou will see that the type isUnboundinstead of the expectedOptional[int]mypyplaygroundIn each of those examples, un-comment out the type annotations and see the errors go away (and/or
errorCodebe properly typed asint | NoneSlots
I believe we use
__slots__here for the memory saving of not carrying a__dict__around on each object. The below script demonstrates that these annotations do not increase the size of each created thrift object. Forward Warning: the PR and description were not generated using AI tools, but this validation script was:Administravia
[skip ci]anywhere in the commit message to free up build resources.