descriptor object for an attribute?

Larry Bates larry.bates at websafe.com
Wed Apr 11 17:29:09 CEST 2007


Eric Mahurin wrote:
> Is there a standard way to get a descriptor object for an arbitrary
> object attribute - independent of whether it uses the descriptor/
> property protocol or not.  I want some kind of handle/reference/
> pointer to an attribute.  I know I could make my own class to do this
> (using the __dict__ of the object and the attribute name), but I would
> like to use something standard (at least a protocol) if it exists.
> All that is needed in the protocol is getter and setter methods (like
> __get__ and __set__ in a descriptor).  Of course it would be nice to
> have a better syntax than those method names of the descriptor (I've
> seen unary + for the getter and += for the setter somewhere on the
> web).
> 
> Now the question I'm going to get is: why?  I've used ruby (everything
> is also already a reference to an object) for several years and been
> through this discussion.  I realize that 90% of the time you want some
> kind of reference/pointer, there is a better way.  But there are those
> occassions where the most elegant solution is with the concept of a
> reference.  An obvious example in python today is a descriptor object
> - it looks just like a reference (but is not a pointer) - having
> getter and setter methods.
> 
> The times in C/C++ where the elegant solution is with a pointer to a
> pointer is also another example.  That is the situation I'm dealing
> with now.  I'm using a singly linked list (as opposed to a normal list/
> array for performance/memory reasons).  If you want to insert/delete a
> node at a certain point in the list, the best thing to have access to
> would be "link" (attribute or even local variable) where you want to
> insert/delete.  Without a reference, you'd end up with a less than
> ideal solution: a) do the operation based on the previous node and
> special case the situation where you want to operate at the head (no
> previous node), b) do the operation based on the previous node and add
> a dummy head node, or c) make the list doubly linked, do the operation
> based on the current node, and either special case the head or add a
> dummy head node.  Really I'm dealing with a directed graph structure,
> but part of it uses singly linked lists (the children of a parent).
> Having a handle on any of the links in the graph would be a useful
> thing.
> 
I believe you are looking for setattr(obj, attr, value) and
getattr(obj, attr) functions.  Since everything in python its a
pointer to an object, I wasn't able to understand EXACTLY what you
were asking (an example would help).

-Larry



More information about the Python-list mailing list