[Python-ideas] Extending properties to sequence-like behavior

Dan Baker dbaker3448 at gmail.com
Wed Apr 6 07:31:18 CEST 2011


I know the property() built-in allows you to override the behavior of
attribute access in a class to call arbitrary functions where the
syntax looks like a basic assign or lookup. This is handy when you're
importing an external API and want to make it look more Pythonic. Is
there a simple way to extend this so that item lookup or assignment
can be similarly overridden? For instance, if the object I'm importing
(say, a drop-down box in a GUI toolkit) has methods called
GetAllItems, SetAllItems, GetItemAtPos, and SetItemAtPos, I want to be
able to translate:

return box.Items -> return box.GetAllItems()
box.Items = itemlist -> box.SetAllItems(itemlist)
return box.Items[idx] -> return box.GetItemAtPos(idx)
box.Items[idx] = new_item -> box.SetItemAtPos(idx, new_item)

Just using property() doesn't quite work; it handles the "set all" and
"get all" operations easily enough, and "get item" works for any
interface that it would be sane to attempt this on by just getting the
appropriate slice of the list returned by "get all" (although this may
be inefficient compared to calling the real "get item" function), but
"set item" doesn't work because it calls "get all" and then assigns to
a slot in the list returned by that function.

The best solution I've come up with so far is to create an object (of
a class I'll call ListProp) and have the "get" function of the
property return this object. Then I can override the __getitem__ and
__setitem__ methods to call the "get item" and "set item" functions.
The "get all" function no longer works exactly as above, though;
box.Items would instead return the ListProp object. This can be solved
by using __call__ on the ListProp as the "get all" method; then the
only change is to use box.Items() for the "get all" function.

I've attached some scratch code here (Python 2.7) demonstrating the
basic idea. Is there a better way to do this?

Dan Baker
-------------- next part --------------
A non-text attachment was scrubbed...
Name: listprop.py
Type: application/octet-stream
Size: 1036 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110406/46a7ead3/attachment.obj>


More information about the Python-ideas mailing list