Generic proxy (that proxies methods like __iter__)

Arnaud Delobelle arnodel at googlemail.com
Wed Jan 27 10:07:23 EST 2010


On 27 Jan, 14:41, D HANNEY <spam2... at nney.com> wrote:
[...]
> >>> class NoGuardProxy(object):
>
> ...         def __init__(self, t):
> ...                 self.t = t
> ...         def __enter__(self):
> ...                 return self
> ...         def __exit__(self, type, value, traceback):
> ...                 return False
> ...         def __getattr__(self):
> ...                 return self.t.__getattr__(self)
> ...>>> show(NoGuardProxy(StringIO.StringIO("blah1\nblah2\nblah3\n")))
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in show
> TypeError: 'NoGuardProxy' object is not iterable
>
> #
> # Now I'm stuck.
> # Can anyone help?
> #

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



More information about the Python-list mailing list