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

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Mar 5 23:53:31 CET 2011


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.

-- 
Greg

> 
> In other news, exploring the pros and cons of x.(foo) and its
> alternatives and variations would also be a fine idea. I find myself
> writing getattr() a lot. Although OTOH I also find myself telling
> people in code reviews a lot how they can avoid the need for using
> getattr(). And OT3H my most common use of getattr() is probably the
> 3-argument variant, as a best-practice alternative to using hasattr().
> 




More information about the Python-ideas mailing list