getting the current function

Arnaud Delobelle arnodel at
Fri Sep 7 19:36:35 CEST 2007

On Sep 7, 5:19 pm, Gary Robinson <gary... at> wrote:
> > This all seems a bit too complicated. Are you sure you want to do
> > this? Maybe you need to step back and rethink your problem.
> In version 2.1 Python added the ability to add function attributes -- see the justifications. A counter probably isn't one of them, I just used that as a quick example of using thisfunc().
> I've just never liked the fact that you have to name the function when accessing those attributes from within the function. And I thought there might be other uses for something like thisfunc().

You can do this without fiddling with stack frames:

def bindfunction(f):
    def bound_f(*args, **kwargs):
        return f(bound_f, *args, **kwargs)
    bound_f.__name__ = f.__name__
    return bound_f

# Use like this:

def factorial(this_function, n):
    if n > 0:
        return n * this_function(n - 1)
        return 1

# Interactively:

>>> factorial(5)
>>> fac = factorial
>>> factorial = "spam"
>>> fac(8)


More information about the Python-list mailing list