[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)

MRAB python at mrabarnett.plus.com
Sun Mar 6 01:32:21 CET 2011


On 05/03/2011 22:53, Greg Ewing wrote:
> Guido van Rossum wrote:
>
>> I think that's a reasonable thought to pursue further. If I could write
>>
>> class Person(Model):
>> name = StringProperty()
>> age = IntegerProperty()
>>
>> without Model needing to have a custom metaclass that goes over the
>> __dict__ and tells each Property instance its name I would take it.
>
> You mean without *any* new syntax?
>
> I suppose that could be done with a suitable protocol, e.g.
> whenever assigning something to a bare name, if it has a
> __setname__ method, call it with the name being assigned to.
>
> That would incur overhead on every assignment to a bare name,
> although if __setname__ is given a type slot it might be
> possible to make the overhead small enough to ignore.
>
> Another problem is that you really only want this to happen
> on the *first* assignment.
>
> Another approach might be to make it a standard part of the
> class creation process to go through the attribute dict
> looking for objects with __setname__ methods and calling
> them. That would mean the feature would only be available
> for objects residing in classes, though, so you wouldn't
> be able to use it to declare named tuples at module level,
> for example.
>
With classes, couldn't that be done just as easily now with a decorator?



More information about the Python-ideas mailing list