[TransWarp] dynamic class binding

Phillip J. Eby pje at telecommunity.com
Mon Mar 31 15:25:54 EST 2003


At 10:46 PM 3/31/03 +0300, alexander smishlajev wrote:
>hello!
>
>please consider the following wrong code example:
>
>    from peak.api import binding
>
>    class A(binding.Component):
>        name = "A"
>        spam = binding.bindToProperty(name + ".spam",
>            default=("beacon and " + name))
>        def getit(self):
>            print repr(self.spam)
>
>    class B(A):
>        name = "B"
>
>    if __name__ == "__main__":
>        B().getit()
>
>the intent was to have the 'spam' property of Component 'B' bound to the 
>config setting 'B.spam' and defaulting to string 'beacon and B'.

Try this:

class A(binding.Component):

     name = "A"

     def spam(self,d,a):
         return config.getProperty(self.name+".spam", self, "beacon and 
"+self.name)

     spam = binding.Once(spam)

     # ... continue as above


>obviously, this approach does not work.

Well, it does what you're *telling* it to do.  You told PEAK to make an 
attribute computed from the property "A.spam", with a default of "beacon 
and A".  There isn't any way to have bindings automatically redefined in a 
subclass at the moment.  (Actually, there is, but it's rather hideously 
complex at the moment and not worth using for this simple application.)


>what is the right way to do such things in PEAK?

See my revisions to your class 'A'.  Note that all 'bindTo()' variations 
are actually implemented by either invoking or subclassing 
'binding.Once()', so if you need to do something that one of the other 
binding techniques doesn't support, you can always write a Once method of 
your own devising.




More information about the PEAK mailing list