



Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Prepara tus exámenes
Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Prepara tus exámenes con los documentos que comparten otros estudiantes como tú en Docsity
Encuentra los documentos específicos para los exámenes de tu universidad
Estudia con lecciones y exámenes resueltos basados en los programas académicos de las mejores universidades
Responde a preguntas de exámenes reales y pon a prueba tu preparación
Consigue puntos base para descargar
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Comunidad
Pide ayuda a la comunidad y resuelve tus dudas de estudio
Ebooks gratuitos
Descarga nuestras guías gratuitas sobre técnicas de estudio, métodos para controlar la ansiedad y consejos para la tesis preparadas por los tutores de Docsity
Este documento proporciona recomendaciones sobre cómo trabajar con annotations en Python. Aborda diferentes aspectos como el acceso al dict de annotations de un objeto en diferentes versiones de Python, las mejores prácticas para usar annotations y algunas peculiaridades a tener en cuenta. Además, ofrece consejos sobre cómo manejar situaciones en las que las annotations están stringizadas y cómo evaluarlas correctamente.
Tipo: Monografías, Ensayos
1 / 5
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!




April 14, 2022 Python Software Foundation Email: [email protected]
1 Accessing The Annotations Dict Of An Object In Python 3.10 And Newer 2
2 Accessing The Annotations Dict Of An Object In Python 3.9 And Older 2
3 Manually Un-Stringizing Stringized Annotations 3
4 Best Practices For annotations In Any Python Version 3
5 annotations Quirks 4
Index 5
author Larry Hastings
Abstract
This document is designed to encapsulate the best practices for working with annotations dicts. If you write Python code that examines annotations on Python objects, we encourage you to follow the guidelines described below. The document is organized into four sections: best practices for accessing the annotations of an object in Python versions 3.10 and newer, best practices for accessing the annotations of an object in Python versions 3.9 and older, other best practices for annotations that apply to any Python version, and quirks of annotations. Note that this document is specifically about working with annotations, not uses for annotations. If you’re looking for information on how to use “type hints” in your code, please see the typing module.
1 Accessing The Annotations Dict Of An Object In Python 3.10 And
Newer
Python 3.10 adds a new function to the standard library: inspect.get_annotations(). In Python versions 3.10 and newer, calling this function is the best practice for accessing the annotations dict of any object that supports annotations. This function can also “un-stringize” stringized annotations for you. If for some reason inspect.get_annotations() isn’t viable for your use case, you may access the annotations data member manually. Best practice for this changed in Python 3.10 as well: as of Python 3.10, o.annotations is guaranteed to always work on Python functions, classes, and modules. If you’re certain the object you’re examining is one of these three specific objects, you may simply use o.annotations to get at the object’s annotations dict. However, other types of callables–for example, callables created by functools.partial()–may not have an annotations attribute defined. When accessing the annotations of a possibly unknown object, best practice in Python versions 3.10 and newer is to call getattr() with three argu- ments, for example getattr(o, 'annotations', None).
2 Accessing The Annotations Dict Of An Object In Python 3.9 And
Older
In Python 3.9 and older, accessing the annotations dict of an object is much more complicated than in newer versions. The problem is a design flaw in these older versions of Python, specifically to do with class annotations. Best practice for accessing the annotations dict of other objects–functions, other callables, and modules–is the same as best practice for 3.10, assuming you aren’t calling inspect.get_annotations(): you should use three-argument getattr() to access the object’s annotations attribute. Unfortunately, this isn’t best practice for classes. The problem is that, since annotations is optional on classes, and because classes can inherit attributes from their base classes, accessing the annotations attribute of a class may inadvertently return the annotations dict of a base class. As an example:
class Base : a: int = 3 b: str = 'abc'
class Derived (Base): pass
print(Derived.annotations)
This will print the annotations dict from Base, not Derived. Your code will have to have a separate code path if the object you’re examining is a class (isinstance(o, type)). In that case, best practice relies on an implementation detail of Python 3.9 and before: if a class has annotations defined, they are stored in the class’s dict dictionary. Since the class may or may not have annotations defined, best practice is to call the get method on the class dict. To put it all together, here is some sample code that safely accesses the annotations attribute on an arbitrary object in Python 3.9 and before:
5 annotations Quirks
In all versions of Python 3, function objects lazy-create an annotations dict if no annotations are defined on that object. You can delete the annotations attribute using del fn.annotations, but if you then access fn.annotations the object will create a new empty dict that it will store and return as its annotations. Deleting the annotations on a function before it has lazily created its annotations dict will throw an AttributeError; using del fn.annotations twice in a row is guaranteed to always throw an AttributeError. Everything in the above paragraph also applies to class and module objects in Python 3.10 and newer. In all versions of Python 3, you can set annotations on a function object to None. However, subsequently accessing the annotations on that object using fn.annotations will lazy-create an empty dictionary as per the first paragraph of this section. This is not true of modules and classes, in any Python version; those objects permit setting annotations to any Python value, and will retain whatever value is set. If Python stringizes your annotations for you (using from future import annotations), and you specify a string as an annotation, the string will itself be quoted. In effect the annotation is quoted twice. For example:
from future import annotations def foo(a: "str"): pass
print(foo.annotations)
This prints {'a': "'str'"}. This shouldn’t really be considered a “quirk”; it’s mentioned here simply because it might be surprising.
Index
P
Python Enhancement Proposals PEP 604, 3