On Sun, Dec 12, 2021 at 12:48:36PM -0800, Paul Bryan wrote:

> But what's being annotated, the type or the attribute?

That's easy to test:


>>> class A:
...     attr: Annotated[int, "Doc string"]
... 
>>> int.__annotations__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'int' has no attribute '__annotations__'


Okay, so it's not the type. *wink*


>>> A.__annotations__
{'attr': typing.Annotated[int, 'Doc string']}


It's the *class* that is annotated. But note that the mapping is between 
the attribute name to annotation, so in the sense that attributes are 
represented by their name, it is the attribute that is annotated.

As it obviously has to be. After all, didn't we *literally* annotate the 
attribute?

    attr: annotation

Don't be fooled by the use of the Annotated pseudo-type as the 
annotation. We're still annotating the attribute, just like the code 
shows, regardless of what type we annotate it as.

If we had written:

    attr: Sequence[int]

there would be no questions about what's being annotated, is it the type 
int or the attribute.

It cannot be the type, because many different objects with many 
different annotations may share the same type.

Unlike modules, classes and functions, the annotation cannot be on the 
attribute's *value*, because the attribute may not even have a value at 
this point. And even if it does, it might be immutable, or like the 
type, many different attributes, with different annotations, may be 
sharing the same value.

This rules out putting the docstring on the attribute directly.

The syntax shows us annotating the attribute, and that's exactly what 
got annotated.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UBGM3KTTH3A7BJXOQCZAAGKNWJ6LBRN4/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to