descriptor object for an attribute?

Eric Mahurin eric.mahurin at gmail.com
Wed Apr 11 11:18:15 EDT 2007


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.




More information about the Python-list mailing list