@@ -34,11 +34,16 @@ Accessing The Annotations Dict Of An Object In Python 3.10 And Newer
3434
3535Python 3.10 adds a new function to the standard library:
3636: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
3838accessing the annotations dict of any object that supports
3939annotations. This function can also "un-stringize"
4040stringized annotations for you.
4141
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+
4247If for some reason :func: `inspect.get_annotations ` isn't
4348viable for your use case, you may access the
4449``__annotations__ `` data member manually. Best practice
@@ -184,7 +189,11 @@ Best Practices For ``__annotations__`` In Any Python Version
184189* If you do assign directly to the ``__annotations__ `` member
185190 of an object, you should always set it to a ``dict `` object.
186191
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
188197 of an object, you should ensure that it's a
189198 dictionary before attempting to examine its contents.
190199
@@ -231,3 +240,11 @@ itself be quoted. In effect the annotation is quoted
231240
232241This prints ``{'a': "'str'"} ``. This shouldn't really be considered
233242a "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