Mangle function name with decorator?

Adam adam.crossland at gmail.com
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.

Example:

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)()
            else:
                return getattr(self, self.method)()
        else:
            if hasattr(self, self.method):
                return getattr(self, self.method)()
            else:
                raise NotImplementedError

    @bar
    def foo(self):
        print "in _bar_foo"

    def foo(self):
        print "in foo"

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





More information about the Python-list mailing list