user3240688
user3240688

Reputation: 1327

How to get current function object in Python?

Is there a way to get the current function I'm in?

I'm looking for the actual function object, not the function name.

    def foo(x,y):
        foo_again = <GET_CURRENT_FUNCTION>
        if foo_again == foo:
            print ("YES they are equal!")

I assume I could do that in Python inspect module, but I can't seem to find it.

EDIT The reason I want that is I want to print out the arguments to my function. And I can do that with inspect. Like this

   def func(x,y):
       for a in inspect.getfullargspec(func).args:
           print (a, locals()[a])

This works, but I don't want to have to manually write the function name. Instead, I want to do

   def func(x,y):
       for a in inspect.getfullargspec(<GET_CURRENT_FUNCTION>).args:
           print (a, locals()[a])

Upvotes: 1

Views: 316

Answers (2)

aerijman
aerijman

Reputation: 2762

from inspect.stack you can get the function's name.

Here is a workaround that might not be optimal but it gives your expected results.

def foo(x,y): 
    this_function = inspect.stack()[0].function 
    for a in inspect.getfullargspec( eval(this_function) ).args: 
        print(a, locals()[a]) 
    print(this_function)

Then

foo('a','b')
>>>
    x a
    y b
    foo

Upvotes: 1

Daniel Walker
Daniel Walker

Reputation: 6740

One way to accomplish this is by using a decorator. Here's an example:

def passFunction(func):
    @functools.wraps(func)
    def new_func(*args, **kwargs):
        return func(func,*args, **kwarsgs)
    return new_func

@passFunction
def foo(f, x, y):
    ...

foo(x,y)

Upvotes: 0

Related Questions