wrapping a method function call?

Aaron Brady castironpi at gmail.com
Mon Nov 3 19:53:09 CET 2008

On Nov 3, 3:57 am, m... at pixar.com wrote:
> Steven D'Aprano <ste... at remove.this.cybersource.com.au> wrote:
> > Now you can monkey patch class A if you want. It's probably not a great
> > idea to do this in production code, as it will effect class A everywhere.
> This is perfect for me.  The code in question is basically a protocol
> translator... it receives requests over the network, makes some calls,
> and returns the result translated back to the original protocol, so there's
> a single instance of each A,B, etc.
> > A.p1 = precall(pre)(postcall(post)(A.p1))
> Is there a way to do this for all callable methods of A? e.g.
>     for x in callable_methods(A):
>         x = precall(pre)(postcall(post)(x))
> Thanks!
> Mark
> --
> Mark Harrison
> Pixar Animation Studios

Hi, that sounds like metaclasses.

from types import *
def pre( self, *ar, **kwar ):
    print 'in pre'
def post( self, *ar, **kwar ):
    print 'in post'
class metacls(type):
    def __new__(mcs, name, bases, dict):
        for k, x in dict.items():
            if isinstance( x, FunctionType ):
                def modx( f ):
                    def _mod( *arg, **kwarg ):
                        pre( *arg, **kwarg )
                        retval= f( *arg, **kwarg )
                        post( *arg, **kwarg )
                        return retval
                    return _mod
                dict[ k ]= modx( x )
        return type.__new__(mcs, name, bases, dict)

class A( object ):
    __metaclass__= metacls
    def f( self ):
        print 'in f'

a= A()


in pre
in f
in post

More information about the Python-list mailing list