On 4/24/21 8:09 AM, Petr Viktorin wrote:
On 24. 04. 21 9:52, Larry Hastings wrote:
I've hit a conceptual snag in this.
What I thought I needed to do: set __annotations__= {} in the module dict, and set __annotations__= {} in user class dicts. The latter was more delicate than the former but I think I figured out a good spot for both. I have this much working, including fixing the test suite.
But now I realize (*head-slap* here): if *every* class is going to have annotations, does that mean builtin classes too? StructSequence classes like float? Bare-metal type objects like complex? Heck, what about type itself?!
My knee-jerk initial response: yes, those too. Which means adding a new getsetdef to the type object. But that's slightly complicated. The point of doing this is to preserve the existing best-practice of peeking in the class dict for __annotations__, to avoid inheriting it. If I'm to preserve that, the get/set for __annotations__ on a type object would need to get/set it on tp_dict if tp_dict was not NULL, and use internal storage somewhere if there is no tp_dict.
It's worth noticing that builtin types don't currently have __annotations__ set, and you can't set them. (Or, at least, float, complex, and type didn't have them set, and wouldn't let me set annotations on them.) So presumably people using current best practice--peek in the class dict--aren't having problems.
So I now suspect that my knee-jerk answer is wrong. Am I going too far down the rabbit hole? Should I /just/ make the change for user classes and leave builtin classes untouched? What do you think?
Beware of adding mutable state to bulit-in (C static) type objects: these are shared across interpreters, so changing them can “pollute” unwanted contexts.
This has been so for a long time [0]. There are some subinterpreter efforts underway that might eventually lead to making __annotations__ on static types easier to add, but while you're certainly welcome to explore the neighboring rabbit hole as well, I do think you're going in too far for now :)
[0] https://mail.python.org/archives/list/python-dev@python.org/message/KLCZIA6F...
That's a good point! The sort of detail one forgets in the rush of the moment. Given that the lack of annotations on builtin types already isn't a problem, and given this wrinkle, and generally given the "naw you don't have to" vibe I got from you and Nick (and the lack of "yup you gotta" I got from anybody else), I'm gonna go with not polluting the builtin types for now. This is not to say that, in the fullness of time, those objects should never have annotations. Even in the three random types I picked in my example, there's at least one example: float.imag is a data member and might theoretically be annotated. But we can certainly kick this can down the road too. Maybe by the time we get around to it, we'll have a read-only dictionary we can use for the purpose. Cheers, //arry/