Use get_annotations instead of direct __annotations__ access
#2196
+19
−10
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.
#2158 changed how pandera fetches annotations in the
DataFrameModel.__init_subclass__method, which can lead to some surprising behavior. For instance, consider the following snippet:As of 0.27.1, the output is
This behavior appears to be related to an issue noted in PEP 749, namely that accessing
__annotations__on a metaclass before accessing__annotations__on a child class causes annotations to leak from the parent class to the child class. In this case, that leakage results inpandera.api.dataframe.model.DataFrameModel.__init_subclass__adding a new field on the child class, but without the alias (or any other properties) that are set on the parent.Per documentation:
Since pandera has dropped support for Python 3.9, the fix here is just to use
inspect.get_annotations(which is an alias for annotationlib.get_annotations in Python 3.14). I'm not quite sure what the rationale for the change in #2158 to check for annotations in__annotations_cache__, but if astral-sh/ruff#17859 is to believed that might also be unsafe.The snippet above is perhaps contrived in that it involves accessing the metaclass's annotations directly for no good reason, but we are hitting real bugs that are preventing us from upgrading beyond 0.26.1, and the changes here resolve them for us.