__getattribute__ and methods proxying

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sat Jun 12 15:47:13 EDT 2010


On 07:01 pm, g.rodola at gmail.com wrote:
>Hi,
>I have a class which looks like the one below.
>What I'm trying to accomplish is to "wrap" all my method calls and
>attribute lookups into a "proxy" method which translates certain
>exceptions into others.
>The code below *apparently* works: the original method is called but
>for some reason the "except" clause is totally ignored.
>
>I thought __getattribute__ was designed for such kind of things
>("proxying") but apparently it seems I was wrong.
>
>
>
>class NoSuchProcess(Exception): pass
>class AccessDenied(Exception): pass
>
>
>class Process(object):
>
>    def __getattribute__(self, name):
>        # wrap all method calls and attributes lookups so that
>        # underlying OSError exceptions get translated into
>        # NSP and AD exceptions
>        try:
>            print "here 1!"
>            return object.__getattribute__(self, name)
>        except OSError, err:
>            print "here 2!"
>            if err.errno == errno.ESRCH:
>                raise NoSuchProcess
>            if err.errno == errno.EPERM:
>                raise AccessDenied
>
>    def cmdline(self):
>        raise OSError("bla bla")
>
>
>proc = Process()
>proc.cmdline()

You've proxied attribute access here.  But no OSError is raised by the 
attribute access.  It completes successfully.  Then, the cmdline method 
which was retrieved by the attribute access is called, normally, with 
none of your other code getting involved.  This raises an OSError, which 
your code doesn't handle because it has already returned.

Jean-Paul



More information about the Python-list mailing list