controlling method execution

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at
Thu Nov 20 10:08:52 CET 2003

mic wrote:
> Is it possible to control method exectution using similiar mechanism as with
> get/setatrribute special methods for attributes? I'd like to have every (or
> some of ) method of class instance run common code defined outside the class
> without making any explicit references to it.
> To give an example, I'd like to prepare secure environment, in which users
> could execute only methods that can be accessed by them. IMO the most
> universal way to do it would be to run automatically authorisation routine
> before every method execution.
> Regards,
> Michal
Here comes my humble attempt:

import inspect
import new

def before():
     print "before"

class WrapperMeta(type):
     def __new__(cls, name, bases, attrs):
         wrapped = {}
         for n, v in attrs.iteritems():
             if inspect.isfunction(v):
                 class Controled(object):
                     def __get__(self, obj, cls):
                         return new.instancemethod(v, obj, cls)

                 wrapped[n] = Controled()
         return super(WrapperMeta, cls).__new__(cls, name, bases, attrs)

class Controled(object):
     __metaclass__ = WrapperMeta

class Test(Controled):
     def method(self, x, y):
         print 'Test.method(%s, %s)' % (x, y)

test = Test()
test.method(10, 11)

I hope gurus will suggest better approaches. However, I'm afraid that 
metaclass approach cannot guarantee enough security: one can simple get 
rid of metaclass to bypass the mechanism.


More information about the Python-list mailing list