Skip to content

Commit 07b8d31

Browse files
gh-132261: Store annotations at hidden internal keys in the class dict (#132345)
1 parent e5f68fd commit 07b8d31

16 files changed

+100
-52
lines changed

Doc/library/annotationlib.rst

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -303,12 +303,12 @@ Functions
303303
.. function:: get_annotate_function(obj)
304304

305305
Retrieve the :term:`annotate function` for *obj*. Return :const:`!None`
306-
if *obj* does not have an annotate function.
306+
if *obj* does not have an annotate function. *obj* may be a class, function,
307+
module, or a namespace dictionary for a class. The last case is useful during
308+
class creation, e.g. in the ``__new__`` method of a metaclass.
307309

308310
This is usually equivalent to accessing the :attr:`~object.__annotate__`
309-
attribute of *obj*, but direct access to the attribute may return the wrong
310-
object in certain situations involving metaclasses. This function should be
311-
used instead of accessing the attribute directly.
311+
attribute of *obj*, but access through this public function is preferred.
312312

313313
.. versionadded:: 3.14
314314

Include/internal/pycore_global_objects_fini_generated.h

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Include/internal/pycore_global_strings.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,9 @@ struct _Py_global_strings {
7878
STRUCT_FOR_ID(__and__)
7979
STRUCT_FOR_ID(__anext__)
8080
STRUCT_FOR_ID(__annotate__)
81+
STRUCT_FOR_ID(__annotate_func__)
8182
STRUCT_FOR_ID(__annotations__)
83+
STRUCT_FOR_ID(__annotations_cache__)
8284
STRUCT_FOR_ID(__args__)
8385
STRUCT_FOR_ID(__await__)
8486
STRUCT_FOR_ID(__bases__)

Include/internal/pycore_magic_number.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ Known values:
274274
Python 3.14a6 3619 (Renumber RESUME opcode from 149 to 128)
275275
Python 3.14a6 3620 (Optimize bytecode for all/any/tuple called on a genexp)
276276
Python 3.14a7 3621 (Optimize LOAD_FAST opcodes into LOAD_FAST_BORROW)
277+
Python 3.14a7 3622 (Store annotations in different class dict keys)
277278
278279
Python 3.15 will start with 3650
279280
@@ -286,7 +287,7 @@ PC/launcher.c must also be updated.
286287
287288
*/
288289

289-
#define PYC_MAGIC_NUMBER 3621
290+
#define PYC_MAGIC_NUMBER 3622
290291
/* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes
291292
(little-endian) and then appending b'\r\n'. */
292293
#define PYC_MAGIC_NUMBER_TOKEN \

Include/internal/pycore_runtime_init_generated.h

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Include/internal/pycore_unicodeobject_generated.h

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Lib/annotationlib.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -619,14 +619,6 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
619619
raise ValueError(f"Invalid format: {format!r}")
620620

621621

622-
# We use the descriptors from builtins.type instead of accessing
623-
# .__annotations__ and .__annotate__ directly on class objects, because
624-
# otherwise we could get wrong results in some cases involving metaclasses.
625-
# See PEP 749.
626-
_BASE_GET_ANNOTATE = type.__dict__["__annotate__"].__get__
627-
_BASE_GET_ANNOTATIONS = type.__dict__["__annotations__"].__get__
628-
629-
630622
def get_annotate_function(obj):
631623
"""Get the __annotate__ function for an object.
632624
@@ -635,12 +627,11 @@ def get_annotate_function(obj):
635627
636628
Returns the __annotate__ function or None.
637629
"""
638-
if isinstance(obj, type):
630+
if isinstance(obj, dict):
639631
try:
640-
return _BASE_GET_ANNOTATE(obj)
641-
except AttributeError:
642-
# AttributeError is raised for static types.
643-
return None
632+
return obj["__annotate__"]
633+
except KeyError:
634+
return obj.get("__annotate_func__", None)
644635
return getattr(obj, "__annotate__", None)
645636

646637

@@ -833,7 +824,7 @@ def _get_and_call_annotate(obj, format):
833824
def _get_dunder_annotations(obj):
834825
if isinstance(obj, type):
835826
try:
836-
ann = _BASE_GET_ANNOTATIONS(obj)
827+
ann = obj.__annotations__
837828
except AttributeError:
838829
# For static types, the descriptor raises AttributeError.
839830
return {}

Lib/pydoc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,8 @@ def visiblename(name, all=None, obj=None):
330330
'__date__', '__doc__', '__file__', '__spec__',
331331
'__loader__', '__module__', '__name__', '__package__',
332332
'__path__', '__qualname__', '__slots__', '__version__',
333-
'__static_attributes__', '__firstlineno__'}:
333+
'__static_attributes__', '__firstlineno__',
334+
'__annotate_func__', '__annotations_cache__'}:
334335
return 0
335336
# Private names are hidden, but special names are displayed.
336337
if name.startswith('__') and name.endswith('__'): return 1

Lib/test/test_ast/test_ast.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def test_arguments(self):
298298
x = ast.arguments()
299299
self.assertEqual(x._fields, ('posonlyargs', 'args', 'vararg', 'kwonlyargs',
300300
'kw_defaults', 'kwarg', 'defaults'))
301-
self.assertEqual(x.__annotations__, {
301+
self.assertEqual(ast.arguments.__annotations__, {
302302
'posonlyargs': list[ast.arg],
303303
'args': list[ast.arg],
304304
'vararg': ast.arg | None,

Lib/test/test_pydoc/test_pydoc.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,6 @@ class A(builtins.object)
7878
| __weakref__%s
7979
8080
class B(builtins.object)
81-
| Methods defined here:
82-
|
83-
| __annotate__(format, /)
84-
|
85-
| ----------------------------------------------------------------------
8681
| Data descriptors defined here:
8782
|
8883
| __dict__%s
@@ -180,9 +175,6 @@ class A(builtins.object)
180175
list of weak references to the object
181176
182177
class B(builtins.object)
183-
Methods defined here:
184-
__annotate__(format, /)
185-
----------------------------------------------------------------------
186178
Data descriptors defined here:
187179
__dict__
188180
dictionary for instance variables

0 commit comments

Comments
 (0)