"once" assigment in Python

DouhetSukd at gmail.com DouhetSukd at gmail.com
Fri Sep 14 09:47:31 CEST 2007


Agree that what you are looking for may not be a good idea.  So make
sure you don't shoot yourself in the foot with it.  You should
probably look into your problem some more.

>>> def once(obj,attrname,value):
... 	if hasattr(obj,attrname):
... 		return
... 	else:
... 		setattr(obj,attrname,value)
...
>>> class Foo:
... 	pass
...
>>> foo = Foo()
>>> once(foo,"a",1)
>>> foo.a
1
>>> once(foo,"b",2)
>>> foo.a
1
>>> def m1(self):
... 	print "i am m1"
...
>>> def m2(self):
... 	print "i am m2"
...
>>> once(Foo,"mx",m1)
>>> foo.mx()
i am m1
>>> once(Foo,"mx",m2)
>>> foo.mx()
i am m1
>>>

This is very generic code, but you could make it specific to a class
and an attribute.  If so look into properties.

class Foo2:

  def _setMyAttr(self,value):
     if hasattr(self,"_myAttr"):
       return
     self._myAttr = value

  def _getMyAttr(self):
     if not hasattr(self,"_myAttr"):
        return "somedefaultvalue"
     return self._myAttr

  myAttr = property(_getMyAttr,_setMyAttr)

Note also :  stay away from __setattr__ until you know what you are
doing and
you know when to use self.__dict__ assignments.  Painful personal
experiences for me.




More information about the Python-list mailing list