Metaclass Question

Shalabh Chaturvedi shalabh at
Thu Oct 7 05:42:41 CEST 2004

Jay Parlar wrote:
> I decided to finally bite the bullet, and become part of the 1% of 
> people who understand metaclasses.


> My class here is close, but the problem is with my 'def new_func'. For 
> some reason I assumed that "new instances" of it would get created for 
> each method being overridden, but they're not.


> Is there any way to make new instances of a function, short of a lambda?

Although new functions are created every time you go over the def 
statement in the loop, the func_name variable inside the function gets 
bound to the same object at the end. The solution is to use another 
function to produce fuctions. Wonder if I made any sense. I couldn't get 
your code to do anything on my machine, though.

Anyways, here is a much simpler version which does the same thing:

def make_func(fname, func):
    def new_func(self, *args, **kw):
       self.current_function = fname
       return func(self, *args, **kw)
    return new_func

class MethodNameGetter(type):

    def __init__(cls, name, bases, dict_):
       super(MethodNameGetter, cls).__init__(name, bases, dict_)

       funcs = [(fname,func) for fname,func in dict_.items() if 
isinstance(func, FunctionType)]

       for fname, func in funcs:
          new_func = make_func(fname, func)
          setattr(cls, fname, new_func)
          setattr(cls, '_old_' + fname, func)


More information about the Python-list mailing list