getting the current function

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


On Sep 7, 5:19 pm, Gary Robinson <gary... at mac.com> 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 -- seehttp://www.python.org/dev/peps/pep-0232/for 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:

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

# Interactively:

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

--
Arnaud





More information about the Python-list mailing list