Mangle function name with decorator?

Adam adam.crossland at
Tue Mar 17 17:35:05 CET 2009

I am using Python 2.5, and I would like to write a decorator (or using
some other elegant, declarative approach) to mangle the name of
function in a class.  I would like to be able to have two methods
declared with the same name, but one of them will have a decorator (or
whatever) that will change the name of one of them.


class A(object):
    def __init__(self, method, usebar = False):
        self.method = method
        self.usebar = usebar

    def __call__(self):
        if self.usebar == True:
            mangled_name = "_bar_" + self.method
            if hasattr(self, mangled_name):
                return getattr(self, mangled_name)()
                return getattr(self, self.method)()
            if hasattr(self, self.method):
                return getattr(self, self.method)()
                raise NotImplementedError

    def foo(self):
        print "in _bar_foo"

    def foo(self):
        print "in foo"

Desired output:
>>>y = A("foo", True)
in _bar_foo
>>>z = A("foo")
in foo

More information about the Python-list mailing list