Welcome, guest | Sign In | My Account | Store | Cart
##
## http://code.activestate.com/recipes/577070-bound-inner-classes/
##

## 
## Copyright 2010-2011 by Alex Martelli and Larry Hastings
## 
## This software is provided 'as-is', without any express or implied
## warranty. In no event will the authors be held liable for any damages
## arising from the use of this software.
## 
## Permission is granted to anyone to use this software for any purpose,
## including commercial applications, and to alter it and redistribute it
## freely, subject to the following restrictions:
## 
## 1. The origin of this software must not be misrepresented; you must not
##   claim that you wrote the original software. If you use this software
##   in a product, an acknowledgment in the product documentation would be
##   appreciated but is not required.
## 
## 2. Altered source versions must be plainly marked as such, and must not be
##   misrepresented as being the original software.
## 
## 3. This notice may not be removed or altered from any source
##   distribution.
##

__all__ = ["BoundInnerClass", "UnboundInnerClass"]

import weakref

class Worker(object):
    def __init__(self, cls):
        self.cls = cls

    def __get__(self, outer, outer_class):
        if not outer:
            return self.cls

        name = self.cls.__name__

        # if we're already cached in outer, use that version
        # (but don't use getattr, that would call __get_ recursively)
        if name in outer.__dict__:
            return outer.__dict__[name]

        wrapper_bases = [self.cls]

        # iterate over cls's bases and look in outer to see
        # if any have bound inner classes in outer.
        # if so, multiply inherit from the bound inner version(s).
        multiply_inherit = False
        for base in self.cls.__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

            bound_inner_base = getattr(outer, base.__name__, None)
            if bound_inner_base:
                attr_bases = getattr(bound_inner_base, "__bases__", (None,))
                # the unbound class is always the first base of
                # the bound inner class.
                if attr_bases[0] == base:
                    inherit_from = bound_inner_base
                    multiply_inherit = True
            wrapper_bases.append(inherit_from)

        Wrapper = self._wrap(outer, wrapper_bases[0])
        Wrapper.__name__ = name
        if multiply_inherit:
            Wrapper.__bases__ = tuple(wrapper_bases)

        # cache in outer
        setattr(outer, name, Wrapper)
        return Wrapper

class BoundInnerClass(Worker):
    def _wrap(self, outer, base):
        wrapper_self = self
        assert outer
        outer_weakref = weakref.ref(outer)
        class Wrapper(base):
            def __init__(self, *args, **kwargs):
                wrapper_self.cls.__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 wrapper_self.cls.__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(Worker):
    def _wrap(self, outer, base):
        class Wrapper(base):
            pass
        return Wrapper


if __name__ == "__main__":
    class Outer(object):
        @BoundInnerClass
        class Inner(object):
            def __init__(self, outer):
                self.outer = outer

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

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

        @BoundInnerClass
        class Subclass2OfInner(Inner.cls):
            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

        @BoundInnerClass
        class MITest(SubclassOfInner.cls, RandomUnboundInner, Subclass2OfInner.cls):
            def __init__(self, outer):
                super(Outer.MITest, self).__init__()
                assert self.outer == outer

        @UnboundInnerClass
        class UnboundSubclassOfInner(Inner.cls):
            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()
        for which in order:
            if which == 1: inner = outer.Inner()
            elif which == 2: subclass = outer.SubclassOfInner()
            elif which == 3: subsubclass = outer.SubsubclassOfInner()
        tests()

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

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

    class InnerChild(outer.Inner):
        pass

    inner_child = InnerChild()

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

Diff to Previous Revision

--- revision 4 2011-02-12 19:11:27
+++ revision 5 2011-02-15 00:22:48
@@ -1,8 +1,33 @@
-#
-# http://code.activestate.com/recipes/577070-bound-inner-classes/
-#
-
-__all__ = ["BoundInnerClass", "UnboundInnerSubclass"]
+##
+## http://code.activestate.com/recipes/577070-bound-inner-classes/
+##
+
+## 
+## Copyright 2010-2011 by Alex Martelli and Larry Hastings
+## 
+## This software is provided 'as-is', without any express or implied
+## warranty. In no event will the authors be held liable for any damages
+## arising from the use of this software.
+## 
+## Permission is granted to anyone to use this software for any purpose,
+## including commercial applications, and to alter it and redistribute it
+## freely, subject to the following restrictions:
+## 
+## 1. The origin of this software must not be misrepresented; you must not
+##   claim that you wrote the original software. If you use this software
+##   in a product, an acknowledgment in the product documentation would be
+##   appreciated but is not required.
+## 
+## 2. Altered source versions must be plainly marked as such, and must not be
+##   misrepresented as being the original software.
+## 
+## 3. This notice may not be removed or altered from any source
+##   distribution.
+##
+
+__all__ = ["BoundInnerClass", "UnboundInnerClass"]
+
+import weakref
 
 class Worker(object):
     def __init__(self, cls):
@@ -29,7 +54,7 @@
             # if we can't find a bound inner base,
             # add the original unbound base instead.
             # this is harmless but helps preserve the original MRO.
-            parent = base
+            inherit_from = base
 
             bound_inner_base = getattr(outer, base.__name__, None)
             if bound_inner_base:
@@ -37,9 +62,9 @@
                 # the unbound class is always the first base of
                 # the bound inner class.
                 if attr_bases[0] == base:
-                    parent = bound_inner_base
+                    inherit_from = bound_inner_base
                     multiply_inherit = True
-            wrapper_bases.append(parent)
+            wrapper_bases.append(inherit_from)
 
         Wrapper = self._wrap(outer, wrapper_bases[0])
         Wrapper.__name__ = name
@@ -53,9 +78,11 @@
 class BoundInnerClass(Worker):
     def _wrap(self, outer, base):
         wrapper_self = self
+        assert outer
+        outer_weakref = weakref.ref(outer)
         class Wrapper(base):
             def __init__(self, *args, **kwargs):
-                wrapper_self.cls.__init__(self, outer, *args, **kwargs)
+                wrapper_self.cls.__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)
@@ -67,13 +94,13 @@
                         ".",
                         self.__class__.__name__,
                         " object bound to ",
-                        repr(outer),
+                        repr(outer_weakref()),
                         " at ",
                         hex(id(self)),
                         ">"])
         return Wrapper
 
-class UnboundInnerSubclass(Worker):
+class UnboundInnerClass(Worker):
     def _wrap(self, outer, base):
         class Wrapper(base):
             pass
@@ -84,26 +111,26 @@
     class Outer(object):
         @BoundInnerClass
         class Inner(object):
-            def __init__(self, parent):
-                self.parent = parent
+            def __init__(self, outer):
+                self.outer = outer
 
         @BoundInnerClass
         class SubclassOfInner(Inner.cls):
-            def __init__(self, parent):
+            def __init__(self, outer):
                 super(Outer.SubclassOfInner, self).__init__()
-                assert self.parent == parent
+                assert self.outer == outer
 
         @BoundInnerClass
         class SubsubclassOfInner(SubclassOfInner.cls):
-            def __init__(self, parent):
+            def __init__(self, outer):
                 super(Outer.SubsubclassOfInner, self).__init__()
-                assert self.parent == parent
+                assert self.outer == outer
 
         @BoundInnerClass
         class Subclass2OfInner(Inner.cls):
-            def __init__(self, parent):
+            def __init__(self, outer):
                 super(Outer.Subclass2OfInner, self).__init__()
-                assert self.parent == parent
+                assert self.outer == outer
 
         class RandomUnboundInner(object):
             def __init__(self):
@@ -112,11 +139,11 @@
 
         @BoundInnerClass
         class MITest(SubclassOfInner.cls, RandomUnboundInner, Subclass2OfInner.cls):
-            def __init__(self, parent):
+            def __init__(self, outer):
                 super(Outer.MITest, self).__init__()
-                assert self.parent == parent
-
-        @UnboundInnerSubclass
+                assert self.outer == outer
+
+        @UnboundInnerClass
         class UnboundSubclassOfInner(Inner.cls):
             pass
 

History