[Python-Dev] Python 3, new-style classes and __class__

Vinay Sajip vinay_sajip at yahoo.co.uk
Sat Nov 19 23:06:20 CET 2011


I was looking through the errors which occur when running the test suite of
Django's py3k branch under Python 3, and one particular set of errors caught my
eye which is unrelated to the bytes/str dance. These errors occur in some Django
utility code, which supplies a SimpleLazyObject (new-style) class [1]. This
implements a proxy, which is initialised using a callable. The callable returns
the object to be wrapped, and it's called when needed to set up the wrapped
instance.

The SimpleLazyObject needs to pretend to be the class of the wrapped object,
e.g. for equality tests. This pretending is done by declaring __class__ as a
property in SimpleLazyObject which fetches and returns the __class__ attribute
of the wrapped object. This approach doesn't work in Python 3, however: the
property named __class__ doesn't show up in the class dict of SimpleLazyObject,
and moreover, there are restrictions on what you can set __class__ to - e.g.
Python complains if you try and set a __class__ attribute on the instance to
anything other than a new-style class.

What's the simplest way in Python 3 of implementing the equivalent approach to
pretending to be a different class? Any pointers appreciated.

Thanks and regards,


Vinay Sajip

[1] http://goo.gl/1Jlbj




More information about the Python-Dev mailing list