Welcome, guest | Sign In | My Account | Store | Cart

I define a 'Component' as an attribute (typing optional) that instances can assign objects to. Nothing special there, but their usefulness comes in with 'Abilities'. If a class inherits from 'ClassWithAbilities', it will be given a special attribute 'abilities' that will grow/shrink when other classes with abilities are assigned to an instances attributes. It increases/decreases the functionality of the instance depending on what objects are assigned to it. All of these abilities are accessed through the 'abilities' attribute. This is a redesign of Recipe 576852, but I believe is different enough to warrant a new recipe.

Python, 308 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# used for filtering out 'builtin' methods upon dir() of custom class
std_class_methods = dir(object)
std_instance_methods = dir(object())

# ------------- Components -------------------------------
class _ComponentAccessor(object):
    def __init__(self):
        # flags to prevent infinite recursion during obj '__get__'
        self._breaks = {}

    def __get__(self, instance, owner):
        # if an 'instance' is passed
        #   return dict of {component attr: component value}
        # else use 'owner'
        #   return dict of {component attr: component obj}
        if instance is None:
            obj = owner
        else:
            obj = instance
        if self._get_break(obj):
            return None
        self._set_break(obj)
        _d = {}
        attrs = [a for a in dir(owner) if a not in std_class_methods]
        for attr in attrs:
            component = getattr(owner, attr)
            if getattr(component, '_is_component', False):
                _d[attr] = getattr(obj, attr)
        self._release_break(obj)
        return _d

    def __set__(self, instance, value):
        raise ValueError("Cannot change a '_ComponentAccessor'")
    def __delete__(self, instance, value):
        raise ValueError("Cannot delete a '_ComponentAccessor'")

    def _get_break(self, obj):
        return self._breaks.get(id(obj), False)
    def _set_break(self, obj):
        self._breaks[id(obj)] = True
    def _release_break(self, obj):
        self._breaks[id(obj)] = False

class ClassWithComponents(object):
    """ inherit from this to provide component introspection """
    # introspection flag
    _utilizes_components = True
    # introspection 'property' (read only) that will return
    #   the class' current Components
    components = _ComponentAccessor()


class Component(object):
    """ the data descriptor to add to a class """
    _is_component = True

    def __init__(self, type=None):
        """ type - verify component is set to an instance
            of 'type' when assigned
        """
        self._type = type
        self._cache = {}    # TODO: make into weakref dict

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self._cache.get(id(instance), None)

    def __set__(self, instance, value):
        # check value against self._type
        if value is not None:
            if self._type is not None and not isinstance(value, self._type):
                raise TypeError("Invalid type '%s' for component! Needs to be '%s'" %\
                    (value.__class__.__name__, self._type.__name__,))
        self._cache[id(instance)] = value

    def __delete__(self, instance):
        del(self._cache[id(instance)])
# ------------- /Components ------------------------------



# ------------- Abilities --------------------------------
class _Ability(object):
    def __init__(self, method_name, *bound_methods):
        self.name = method_name
        # TODO: could look at method # of args, etc...
        self._methods = []
        for bm in bound_methods:
            self.append(bm)

    def __str__(self):
        return self.name

    def __call__(self, *args, **kwargs):
        if len(self._methods) == 0:
            return None
        elif len(self._methods) == 1:
            # only 1 method, return its return value
            return self._methods[0](*args, **kwargs)
        else:
            # call all of our methods in order, no return value
            for m in self._methods:
                m(*args, **kwargs)

    def __add__(self, other):
        if not isinstance(other, _Ability):
            raise TypeError("Can only add _Abilities together!")
        if other.name != self.name:
            raise ValueError("Abilities have mismatched names!")
        meth_list = self._methods + other._methods
        return _Ability(self.name, *meth_list)

    def append(self, bound_method):
        if bound_method in self._methods:
            raise ValueError("Cannot add duplicate methods to ability!")
        self._methods.append(bound_method)


class _AbilityAccessor(tuple):
    """ placeholder object for ability methods """
    def __new__(cls, abilities=None):
        if abilities is None:
            abilities = []
        # check for duplicate ability.names combine them
        _ab_d = {}
        for abil in abilities:
            if abil.name not in _ab_d:
                _ab_d[abil.name] = []
            _ab_d[abil.name].append(abil)
        abilities = []
        for name, ab_list in _ab_d.items():
            abil = ab_list.pop(0)
            for ab in ab_list:
                abil += ab
            abilities.append(abil)
        return tuple.__new__(cls, abilities)

    def __init__(self, abilities=None):
        tuple.__init__(self)
        # create a method on self to pass call onto ability
        # ignore passed in 'abilities' arg, use self
        for ab in self:
            object.__setattr__(self, ab.name, ab)

    def __add__(self, other):
        if isinstance(other, _AbilityAccessor):
            abs = tuple.__add__(self, other)
        elif isinstance(other, _Ability):
            abs = []
            abs.extend(self)
            abs.append(other)
        else:
            raise TypeError("Can only add to other _AbilityAccessors!")
        return _AbilityAccessor(abs)


class _AbilityLookup(object):
    def __init__(self):
        # dict of flags to prevent infinite recursion during '__get__'
        self._breaks = {}    # id(obj) -> True/False

    def __get__(self, instance, owner):
        # if an 'instance' is passed
        #   return dict of {ability attr: [ability value]}
        # else use 'owner'
        #   return dict of {ability attr: ability obj}
        _d = {}
        if instance is None:
            if self._get_break(owner):
                return None
            self._set_break(owner)
            attrs = [a for a in dir(owner) if a not in std_class_methods]
            for attr in attrs:
                obj = getattr(owner, attr)
                if getattr(obj, '_is_ability_method', False):
                    _d[attr] = obj
            self._release_break(owner)
            return _d
        else:
            if self._get_break(instance):
                return None
            self._set_break(instance)
            ability_accessor = _AbilityAccessor()
            attrs = [a for a in dir(instance) if a not in std_instance_methods]
            for attr in attrs:
                obj = getattr(instance, attr)
                # check if the obj is an ability method
                if getattr(obj, '_is_ability_method', False):
                    ability_accessor += _Ability(attr, obj)
                # else check if the obj is a class with abilities
                elif getattr(obj, '_utilizes_abilities', False):
                    # get that obj's abilities and extend ours
                    ability_accessor += obj.abilities
            self._release_break(instance)
            return ability_accessor

    def __set__(self, instance, value):
        raise ValueError("Cannot change an '_AbilityLookup'")
    def __delete__(self, instance, value):
        raise ValueError("Cannot delete an '_AbilityLookup'")

    def _get_break(self, obj):
        return self._breaks.get(id(obj), False)
    def _set_break(self, obj):
        self._breaks[id(obj)] = True
    def _release_break(self, obj):
        self._breaks[id(obj)] = False

def abilitymethod(func):
    """ method decorator to mark it as an 'abilitymethod' """
    # check if func has an 'invalid' name
    if func.func_name in dir(_AbilityAccessor):
        raise ValueError("Invalid name for an abilitymethod! '%s'" %\
                (func.func_name,))
    func._is_ability_method = True
    return func

class ClassWithAbilities(object):
    """ inherit from this to provide ability introspection """
    _utilizes_abilities = True
    abilities = _AbilityLookup()

# ------------- /Abilities -------------------------------


if __name__ == "__main__":
    class RobotFirmware(ClassWithAbilities):
        @abilitymethod
        def power_on(self):
            print 'RobotFirmware.power_on'
            self.power_on_checks()

        def power_on_checks(self):
            """ demonstrates object encapsulation of methods """
            print 'RobotFirmware.power_on_checks'

    class UpgradedRobotFirmware(RobotFirmware):
        @abilitymethod
        def laser_eyes(self, wattage):
            print "UpgradedRobotFirmware.laser_eyes(%d)" % wattage

    class RobotArm(ClassWithAbilities):
        @abilitymethod
        def power_on(self):
            print 'RobotArm.power_on'

        @abilitymethod
        def bend_girder(self):
            print 'RobotArm.bend_girder'



    class Robot(ClassWithComponents, ClassWithAbilities):
        firmware = Component(RobotFirmware)
        arm = Component()

        @abilitymethod
        def power_on(self):
            print 'Robot.power_on'

        def kill_all_humans(self):
            """ demonstrates a method that components didn't take over """
            print 'Robot.kill_all_humans'


    print '-- Components --------'
    print 'Robot.components:', Robot.components
    r = Robot()
    print 'r.components:    ', r.components
    print '\tuploading firmware to robot...'
    try:
        r.firmware  = RobotArm()
    except Exception, e:
        print "\tMALFUNCTION! %s" % (e,)
    print '\tuploading firmware to robot try #2...'
    r.firmware = RobotFirmware()
    print '\t...success'
    print 'r.components:    ', r.components
    del(r)
    print '----------------------'
    print ''
    print '-- Abilities ---------'
    print "Robot.abilities:", Robot.abilities
    r = Robot()
    print "r.abilities:    ", r.abilities
    print "r.abilities (by name): ", [ab.name for ab in r.abilities]
    print '\tuploading firmware to robot...'
    r.firmware = RobotFirmware()
    print "r.abilities (by name): ", [ab.name for ab in r.abilities]
    print "r.firmware.abilities:  ", r.firmware.abilities
    print '\tattaching arm to robot...'
    r.arm = RobotArm()
    print "r.abilities (by name): ", [ab.name for ab in r.abilities]
    print "\twhat abilities does 'UpgradedRobotFirmware' provide?"
    print "\t", [x for x in UpgradedRobotFirmware.abilities]
    print "\tOooh laser eyes! upgrading...",
    r.firmware = UpgradedRobotFirmware()
    print "...done"
    print "\tPowering on..."
    r.abilities.power_on()
    print "\tTesting out laser eyes"
    r.abilities.laser_eyes(300)
    print "\tDeleting firmware"
    r.firmware = None
    print "\tPowering on..."
    r.abilities.power_on()
    print '----------------------'

Alright, as I said in my description this is a re-implementation of Recipe 576852, and I believe that there is enough difference to provide another recipe. If there is a better 'standard' way to link two recipes please let me know. The ways in which I believe that this way is superior than the other recipe are listed:

  1. The class (Robot) in my example must specify through inheritance that it is a class that has abilities and components and they will not be attached/utilized without its awareness
  2. An instance's 'abilities' are now localized and called through the 'abilities' attribute instead of methods being assigned on the instance and appearing like regular methods
  3. (goes with 2) An instances abilities are grouped together to provide more flexibility for introspection by outside objects that want to query what abilities the instance provides.
  4. If you don't want the ability call to go through the tree, the instance can bypass the 'combined' abilities by calling the method locally instead of through the 'abilities' attribute. (e.g. r.power_on() instead of r.abilities.power_on())

A bit more discussion on the component stuff. It really is nothing too special and the 'abilities' mechanisms would work fine without the 'component' mechanisms (and vice versa). However, I believe that they work well together which is why I included both in my code.

This recipe probably won't set any speed/efficiency records because the instance's abilities are regenerated upon every call to attributes.__get__ among other reasons, but I believe that this provides for much more dynamic introspection. I can provide a generalized description of how this works, and would be glad to answer any questions. Play with it, tell me where it's lacking and pick it apart. Thanks!

1 comment

Danny G (author) 14 years, 8 months ago  # | flag

So after lengthy reading concerning a design somewhat similar to this, I see that "component architecture" is probably not the correct/proper software design describing this structure. It is probably a mix of strategy pattern, multi-dispatch, and a couple others.

Created by Danny G on Thu, 23 Jul 2009 (MIT)
Python recipes (4591)
Danny G's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks