@@ -34,11 +34,16 @@ Accessing The Annotations Dict Of An Object In Python 3.10 And Newer
34
34
35
35
Python 3.10 adds a new function to the standard library:
36
36
:func: `inspect.get_annotations `. In Python versions 3.10
37
- and newer , calling this function is the best practice for
37
+ through 3.13 , calling this function is the best practice for
38
38
accessing the annotations dict of any object that supports
39
39
annotations. This function can also "un-stringize"
40
40
stringized annotations for you.
41
41
42
+ In Python 3.14, there is a new :mod: `annotationlib ` module
43
+ with functionality for working with annotations. This
44
+ includes a :func: `annotationlib.get_annotations ` function,
45
+ which supersedes :func: `inspect.get_annotations `.
46
+
42
47
If for some reason :func: `inspect.get_annotations ` isn't
43
48
viable for your use case, you may access the
44
49
``__annotations__ `` data member manually. Best practice
@@ -184,7 +189,11 @@ Best Practices For ``__annotations__`` In Any Python Version
184
189
* If you do assign directly to the ``__annotations__ `` member
185
190
of an object, you should always set it to a ``dict `` object.
186
191
187
- * If you directly access the ``__annotations__ `` member
192
+ * You should avoid accessing ``__annotations__ `` directly on any object.
193
+ Instead, use :func: `annotationlib.get_annotations ` (Python 3.14+)
194
+ or :func: `inspect.get_annotations ` (Python 3.10+).
195
+
196
+ * If you do directly access the ``__annotations__ `` member
188
197
of an object, you should ensure that it's a
189
198
dictionary before attempting to examine its contents.
190
199
@@ -231,3 +240,11 @@ itself be quoted. In effect the annotation is quoted
231
240
232
241
This prints ``{'a': "'str'"} ``. This shouldn't really be considered
233
242
a "quirk"; it's mentioned here simply because it might be surprising.
243
+
244
+ If you use a class with a custom metaclass and access ``__annotations__ ``
245
+ on the class, you may observe unexpected behavior; see
246
+ :pep: `749 <749#pep749-metaclasses >` for some examples. You can avoid these
247
+ quirks by using :func: `annotationlib.get_annotations ` on Python 3.14+ or
248
+ :func: `inspect.get_annotations ` on Python 3.10+. On earlier versions of
249
+ Python, you can avoid these bugs by accessing the annotations from the
250
+ class's ``__dict__ `` (e.g., ``cls.__dict__.get('__annotations__', None) ``).
0 commit comments