Descriptors and side effects

mrkafk at gmail.com mrkafk at gmail.com
Mon Nov 5 02:38:53 EST 2007


Hello everyone,

I'm trying to do seemingly trivial thing with descriptors: have
another attribute updated on dot access in object defined using
descriptors.

For example, let's take a simple example where you set an attribute s
to a string and have another attribute l set automatically to its
length.

>>> class Desc(str):
	def __init__(self,val):
		self.s=val
		self.l=len(val)
		print "creating value: ", self.s
		print "id(self.l)", id(self.l)
	def __set__(self, obj, val):
		self.s=val
		self.l=len(val)
		print "setting value:", self.s, "length:", self.l
	def __get__(self, obj, type=None):
		print "getting value:", self.s, "length:", self.l
		return self.l


>>> class some(str):
	m=Desc('abc')
	l=m.l


creating value:  abc
id(self.l) 10049688
>>> ta=some()
>>> ta.m='test string'
setting value: test string length: 11

However, the attribute ta.l didn't get updated:

>>> ta.l
3

This is so much weirder that object id of ta.l is the same as id of
instance of descriptor:

>>> id(ta.l)
10049688

A setter function should have updated self.l just like it updated
self.s:

	def __set__(self, obj, val):
		self.s=val
		self.l=len(val)
		print "setting value:", self.s, "length:", self.l

Yet it didn't happen.

>From my POV, the main benefit of a descriptor lies in its side effect:
on dot access (getting/setting) I can get other attributes updated
automatically: say, in class of Squares I get area automatically
updated on updating side, etc.

Yet, I'm struggling with getting it done in Python. Descriptors are a
great idea, but I would like to see them implemented in Python in a
way that makes it easier to get desireable side effects.




More information about the Python-list mailing list