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

An alternate implementation approach for bound inner classes. For a description of bound inner classes, see this recipe: http://code.activestate.com/recipes/577070-bound-inner-classes/

This recipe works in both Python 2.6 and 3.1.

Python, 230 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
"""

An alternate implementation of bound inner classes.
    http://code.activestate.com/recipes/577623-bound-inner-classes-using-an-alternate-approach/

See also, the original approach:
    http://code.activestate.com/recipes/577070-bound-inner-classes/

Copyright (C) 2011 by Larry Hastings

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

__all__ = ["BindingOuterClass", "BoundInnerClass", "UnboundInnerClass"]

import weakref


class BindingOuterClass(object):
    def __getattribute__(self, name):
        attr = super(BindingOuterClass, self).__getattribute__(name)
        bind_request = getattr(attr, '_binding_class', False)
        suitable = isinstance(attr, type) and bind_request
        if not suitable:
            return attr

        wrapper_bases = [attr]

        # iterate over attr's bases and look in self to see
        # if any have bound inner classes in self.
        # if so, multiply inherit from the bound inner version(s).
        multiply_inherit = False

        for base in attr.__bases__:
            # if we can't find a bound inner base,
            # add the original unbound base instead.
            # this is harmless but helps preserve the original MRO.
            inherit_from = base

            # if we inherit from a boundinnerclass from another outer class,
            # we might have the same name as a legitimate base class.
            # but if we look it up, we'll call __get__ recursively... forever.
            # if the name is the same as our own name, there's no way it's a
            # bound inner class we need to inherit from, so just skip it.
            if base.__name__ != name:
                bound_inner_base = getattr(self, base.__name__, None)
                if bound_inner_base:
                    bases = getattr(bound_inner_base, "__bases__", (None,))
                    # the unbound class is always the first base of
                    # the bound inner class.
                    if bases[0] == base:
                        inherit_from = bound_inner_base
                        multiply_inherit = True
            wrapper_bases.append(inherit_from)

        Wrapper = attr._binding_class(attr, self, wrapper_bases[0])
        Wrapper.__name__ = name

        # Assigning to __bases__ is startling, but it's the only way to get
        # this code working simultaneously in both Python 2 and Python 3.
        if multiply_inherit:
            Wrapper.__bases__ = tuple(wrapper_bases)

        # cache in self
        setattr(self, name, Wrapper)

        return Wrapper


class BoundInnerClass(object):
    @staticmethod
    def _binding_class(attr, outer, base):
        assert outer
        outer_weakref = weakref.ref(outer)
        class Wrapper(base):
            # occlude the original _binding_class!
            # otherwise we'll recurse forever.
            _binding_class = None
            def __init__(self, *args, **kwargs):
                attr.__init__(self, outer_weakref(), *args, **kwargs)

            # give the bound inner class a nice repr
            # (but only if it doesn't already have a custom repr)
            if attr.__repr__ is object.__repr__:
                def __repr__(self):
                    return "".join([
                        "<",
                        self.__module__,
                        ".",
                        self.__class__.__name__,
                        " object bound to ",
                        repr(outer_weakref()),
                        " at ",
                        hex(id(self)),
                        ">"])

        return Wrapper


class UnboundInnerClass(object):
    @staticmethod
    def _binding_class(attr, outer, base):
        class Wrapper(base):
            # occlude the original _binding_class!
            # otherwise we'll recurse forever.
            _binding_class = None

        return Wrapper


# The code in this "if" statement will only execute if you run the module
# directly; it won't run if you "import" this code into your own programs.
if __name__ == "__main__":
    class Outer(BindingOuterClass):
        class Inner(BoundInnerClass):
            def __init__(self, outer):
                self.outer = outer

        class SubclassOfInner(Inner):
            def __init__(self, outer):
                super(Outer.SubclassOfInner, self).__init__()
                assert self.outer == outer

        class SubsubclassOfInner(SubclassOfInner):
            def __init__(self, outer):
                super(Outer.SubsubclassOfInner, self).__init__()
                assert self.outer == outer

        class Subclass2OfInner(Inner):
            def __init__(self, outer):
                super(Outer.Subclass2OfInner, self).__init__()
                assert self.outer == outer

        class RandomUnboundInner(object):
            def __init__(self):
                super(Outer.RandomUnboundInner, self).__init__()
                pass

        class MultipleInheritanceTest(SubclassOfInner,
                     RandomUnboundInner,
                     Subclass2OfInner):
            def __init__(self, outer):
                super(Outer.MultipleInheritanceTest, self).__init__()
                assert self.outer == outer

        class UnboundSubclassOfInner(UnboundInnerClass, Inner):
            pass


    def tests():
        assert outer.Inner == outer.Inner
        assert isinstance(inner, outer.Inner)
        assert isinstance(inner, Outer.Inner)

        assert isinstance(subclass, Outer.SubclassOfInner)
        assert isinstance(subclass, outer.SubclassOfInner)
        assert isinstance(subclass, Outer.Inner)
        assert isinstance(subclass, outer.Inner)

        assert isinstance(subsubclass, Outer.SubsubclassOfInner)
        assert isinstance(subsubclass, outer.SubsubclassOfInner)
        assert isinstance(subsubclass, Outer.SubclassOfInner)
        assert isinstance(subsubclass, outer.SubclassOfInner)
        assert isinstance(subsubclass, Outer.Inner)
        assert isinstance(subsubclass, outer.Inner)

    import itertools

    for order in itertools.permutations([1, 2, 3]):
        outer = Outer()
        # This strange "for" statement lets us test every possible order of
        # initialization for the "inner" / "subclass" / "subsubclass" objects.
        for which in order:
            if which == 1: inner = outer.Inner()
            elif which == 2: subclass = outer.SubclassOfInner()
            elif which == 3: subsubclass = outer.SubsubclassOfInner()
        tests()

    multiple_inheritance_test = outer.MultipleInheritanceTest()
    assert outer.MultipleInheritanceTest.mro() == [
        # bound inner class, notice lowercase-o "outer"
        outer.MultipleInheritanceTest,
        # unbound inner class, notice uppercase-o "Outer"
        Outer.MultipleInheritanceTest,
        outer.SubclassOfInner, # bound
        Outer.SubclassOfInner, # unbound
        Outer.RandomUnboundInner, # etc.
        outer.Subclass2OfInner,
        Outer.Subclass2OfInner,
        outer.Inner,
        Outer.Inner,
        BoundInnerClass,
        object
        ]

    unbound = outer.UnboundSubclassOfInner()
    assert outer.UnboundSubclassOfInner.mro() == [
        outer.UnboundSubclassOfInner,
        Outer.UnboundSubclassOfInner,
        UnboundInnerClass,
        outer.Inner,
        Outer.Inner,
        BoundInnerClass,
        object
        ]

    class InnerChild(outer.Inner):
        pass

    inner_child = InnerChild()

    isinstance(inner_child, Outer.Inner)
    isinstance(inner_child, InnerChild)
    isinstance(inner_child, outer.Inner)

Overview

This recipe presents an alternate implementation of the "bound inner classes" seen in the following recipe:

http://code.activestate.com/recipes/577070-bound-inner-classes/

Rather than re-explain myself here, please read that page to acquaint yourself with bound inner classes and the original implementation.

This Alternate Approach

The original implementation uses some powerful magic: BoundInnerClass is a class decorator which implements the descriptor protocol; the decorated class is subclassed, and the __init__ method of that subclass contains a weakref to the outer "bound" object. (This makes the original recipe almost a checklist of modern Python buzzwords.)

This recipe's approach is slightly simpler. Instead of decorators and the descriptor protocol, it uses inheritance and the __getattribute__() magic method.

To use: first, any outer class containing bound inner classes must be a subclass of BindingOuterClass. Next, inner classes must descend from either BoundInnerClass or UnboundInnerClass, following the rules of the original recipe.

Internally, BindingOuterClass adds __getattribute__() to the outer class. This magic method is called for every attribute lookup on an outer class instance. When code requests an attribute of an outer class instance, __getattribute__() is called. First it gets the value of the attribute using the super() implementation. Next, it checks to see if the result is a class (type type) which itself has an attribute called _binding_class. If not, it returns the attribute unchanged. But if the value of the attribute passes these tests, __getattribute__() binds that class to the outer instance (using the same basic mechanism used in the original recipe) and returns the result.

This recipe is shorter and arguably conceptually easier than the original. So what's the downside? It's the use of __getattribute__(). Since this method is called for every attribute lookup, it levies a heavy toll on performance. This approach also uses an additional magic attribute, _binding_class, which unfortunately must be left in the bound inner classes.

I'm using bound inner classes in my own projects, and I expect to stick with the original recipe.

Revision History

Revision 1 was the original revision.

Revision 2 added the self-referential URL to the source code. (You can't get the URL of a recipe until you submit it, at which point you've created Revision 1.)

Created by Larry Hastings on Thu, 24 Mar 2011 (MIT)
Python recipes (4591)
Larry Hastings's recipes (2)

Required Modules

Other Information and Tasks