Wrapper objects

Egil M?ller redhog at takeit.se
Thu Dec 9 15:11:41 CET 2004

Is there any way to create transparent wrapper objects in Python?

I thought implementing __getattribute__ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:

class Foo(object):
    class __metaclass__(type):
        def __getattribute__(self, name):
            print "Klass", name
            return type.__getattribute__(self, name)
    def __getattribute__(self, name):
        print "Objekt", name
        return object.__getattribute__(self, name)

>>> Foo() + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'Foo' and 'int'
>>> Foo().__add__(1)
Objekt __add__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 8, in __getattribute__
AttributeError: 'Foo' object has no attribute '__add__'

Thus, note that a + b does not do

    return a.__add__(b)
    return b.__radd__(a)

and neither, as I first thought

    return type(a).__add__(a, b)

but something along the lines of

    return type.__getattribute__(type(a), '__add__')(a, b)

So my naive implementation of a wrapper class,

class wrapper(object):
    def __init__(self, value, otherdata):
        self.value = value
        self.otherdata = otherdata
    def __getattribute__(self, name):
        return getattr(self.value, name)

does not work. Any ideas for a solution?

More information about the Python-list mailing list