property puzzle

george young gry at ll.mit.edu
Thu Aug 26 12:46:25 EDT 2004


[python 2.3.3, x86 linux, part of a substantial gtk/postgres app]
I want a Run instance to have a Status instance which inherits
from Observable. I want to be able to say:
 
    thisrun.status = 'planned'

and have thisrun's _set_status do side-effects and then the status
object's setter incorporate the new value as it's new state.
But the setter functions never seem to get called. 
Am I using "property" wrong?

class Observable:              #("observer" software pattern)
    def __init__(self):
        self.observers = []
    def register(self, func, *args, **kw):
        self.observers.append((func, args, kw))
    def notify(self):
        for func, args, kw in self.observers: func(*args, **kw)

class RunStatus(Observable):
     def __init__(self, val):
         Observable.__init__(self)
         self._value = val
     def set(self, newval):
         print 'RunStatus.set'
         self._value = newval
         self.notify()
     def get(self):
         print 'RunStatus.get'
         return self._value
    
class Run:
    def __init__(self):
        self._status = RunStatus('planned')
    def _get_status(self):
        return self._status
    def _set_status(self, val):
        # do various things with val...
        self._status.set(val)
    status = property(_get_status, _set_status)
    
if __name__ == '__main__':
    def stat_display():
        print 'display to screen: r.status=', r.status
    r = Run()
    r.status.register(stat_display) #many registers in real app.
    r.status='hold'
    print 'status=', r.status
    print r._status.observers

Status needs to be a real and persistant object so it's
observers persist, but needs it's value changed simply, like
   r.status = 'something'

[flames about using string values for what is semantically a
 six valued enum *are* welcome in a separate thread...]



More information about the Python-list mailing list