2.2.1.1 Deriving from binding.Component

As we've already seen, attribute bindings can be made to work with ``old-style" or ``classic" Python classes. There are some drawbacks to that, however. Most visibly, it's necessary to specify an attribute binding's name in its definition, as we saw in our example, i.e. "passengers = binding.Make(dict, attrName='passengers')".

However, if we derive our class from binding.Component, we no longer have to do this:

>>> class Car(binding.Component):
        passengers = binding.Make(dict)

>>> aCar=Car()
>>> print aCar.passengers
{}

Now, it's sufficient to use "binding.Make(dict)" to define the attribute. What would happen if we did this without binding.Component?

>>> class Car(object):     # new-style class error messages are more helpful
        passengers = binding.Make(dict)

>>> aCar=Car()
>>> print aCar.passengers
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in ?
    print aCar.passengers
  File "C:\cygwin\home\pje\PEAK\src\peak\binding\once.py", line 420, in __get__
    return self._installedDescr(ob.__class__).__get__(ob,typ)
  File "C:\cygwin\home\pje\PEAK\src\peak\binding\once.py", line 449, in _installedDescr
    self.usageError()
  File "C:\cygwin\home\pje\PEAK\src/peak/binding/_once.pyx", line 125, in _once.BaseDescriptor.usageError
    raise TypeError(
TypeError: Binding was used in a type which does not support active
bindings, but a valid attribute name was not supplied

Ouch! It doesn't work, because PEAK can't tell what name the attribute has without help from either you or the base class. (Actually, it's the metaclass, not the base class, but that's not important right now). There are some circumstances where PEAK will try to guess the attribute name for you, such as when you use a class or a function to define an attribute binding, but for the most part you must either have a base class (such as binding.Component) whose metaclass supports activating bindings, or else you must supply the attribute name yourself when defining the binding.

So, if you plan to use attribute bindings in your program, it's probably best to subclass binding.Component; it'll save you a lot of typing! Most PEAK framework classes for ``service" components derive from binding.Component already.