[Python-Dev] New syntax for 'dynamic' attribute access

Larry Hastings larry at hastings.org
Tue Feb 13 17:29:23 CET 2007


Nick Coghlan wrote:
> I've tried this out on Brett's urllib & urllib2 examples below. (calling 
> the new builtin attrview() to emphasise the fact that it retains a 
> reference to the original instance).

Ooh, ooh!  I wanna change my vote!  +1 on attrview(), +0.25 on ".[]".

Maybe I haven't written enough Python, but I don't think you need this 
specialized form of accessing attributes very often.  So I've shifted to 
the "new syntax seems like overkill" camp.  Besides, once you've got the 
attrview() you can use all the existing dict syntax and it looks totally 
clean.  The original example:
    setattr(self, method_name, getattr(self.metadata, method_name)
which became in the new syntax:
    self.[method_name] = self.metadata.[method_name]
would be:
    attrview(self)[method_name] = attrview(self.metadata)[method_name]
And an attrview lets you use get() and the in operator.  Plus, if you 
were performing a lot of operations on attributes all at one go, you'd 
cache it in a local and then it'd look even better.

Perhaps object.__attrs__() returns a view on the object's attributes, 
and attrview() is simply a convenience function.


/larry/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20070213/f770d913/attachment.html 


More information about the Python-Dev mailing list