Can a function access its own name?

B Mahoney mrbmahoney at gmail.com
Sun Nov 20 04:40:28 CET 2005


Decorate any function with @aboutme(), which
will print the function name each time the function is called.

All the 'hello' stuff is in the aboutme() decorator code.
There is no code in the decorated functions themselves
doing anything to telling us the function name.


# The decorator
def aboutme():

    def thecall(f, *args, **kwargs):
        # Gets to here during module load of each decorated function

        def wrapper( *args, **kwargs):
        # Our closure, executed when the decorated function is called
            print "Hello\nthe name of this function is '%s'\n" \
                % f.func_name
            return f(*args, **kwargs)

        return wrapper

    return thecall

@aboutme()
def testing(s):
    print "string '%s' is argument for function" % s


@aboutme()
def truing():
    return True

# Try these 
testing('x')

testing('again')

truing()




More information about the Python-list mailing list