Generic proxy (that proxies methods like __iter__)

D HANNEY spam2008 at nney.com
Thu Jan 28 08:31:36 EST 2010


On Jan 27, 3:07 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On 27 Jan, 14:41, D HANNEY <spam2... at nney.com> wrote:
> [...]
>
> See [1] for an explanation.  Here is an idea: you could get round that
> by generating a class on the fly, if you don't mind changing the class
> of the object (untested):
>
> def noguardproxy(obj):
>     class NoGuardProxy(type(obj)):
>         def __enter__(self):
>                return self
>         def __exit__(self, type, value, traceback):
>                return False
>     obj.__class__ = NoGuardProxy
>     return obj
>
> If you want to keep obj untouched, you could add the line
>
>     obj = copy(obj)
>
> before changing the class.
>
> --
> Arnaud
>
> [1]http://docs.python.org/reference/datamodel.html#new-style-special-lookup

Thank you!

Your solution works if I change "type(obj)" to say "obj.__class__".
If I don't make this change Python complains "TypeError: Error when
calling the metaclass bases type 'instance' is not an acceptable base
type".
So, I've got something that works but I don't understand why it works.
I've read your docs.python reference but that hasn't helped yet. It
might come to me but in the meantime, can you (or anyone) offer an
explanation for this?

Thanks in advance,

David



More information about the Python-list mailing list