Skip to content

gh-161912: Try calling __annotate__ functions with Format.VALUE before using fake globals in call_annotate_function - #162152

Open
DavidCEllis wants to merge 4 commits into
python:mainfrom
DavidCEllis:161912-annotationlib-try-value-before-fake-globals
Open

DavidCEllis wants to merge 4 commits into
python:mainfrom
DavidCEllis:161912-annotationlib-try-value-before-fake-globals

Conversation

@DavidCEllis

@DavidCEllis DavidCEllis commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This makes call_annotate_function(annotate, Format=Format.FORWARDREF) try annotate(Format.VALUE) before constructing a fake globals dict and using Format.VALUE_WITH_FAKE_GLOBALS.

This call is used in places like TypedDict to get the annotations in a metaclass. In cases where Format.VALUE would succeed, trying it first is significantly faster especially in cases like #161912 where the globals dict is large and copying it is expensive.

Tools that use get_annotations already effectively have this fast path as get_annotations tries __annotations__ first which will use Format.VALUE. As such this adds a _skip_value_call to call_annotate_function to skip retrying that when being used from get_annotations.

There were a few tests that checked using Format.FORWARDREF would use Format.VALUE_WITH_FAKE_GLOBALS always and not use Format.VALUE. These tests have been updated to check both that Format.VALUE is used and that Format.VALUE_WITH_FAKE_GLOBALS is still used if Format.VALUE fails.

Some tests checked VALUE_WITH_FAKE_GLOBALS was always called by defining annotate
functions that were different.

These now test this only if the VALUE format fails.

Adds tests for the expected call order in Format.FORWARDREF failure and for avoiding a
double `VALUE` call in get_annotations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant