1

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])
4
  • i updated question Commented Sep 9, 2020 at 23:44
  • 1
    What's so bad about writing the function name? Commented Sep 9, 2020 at 23:52
  • i plan to copy and paste these 2 lines of code to all functions that i want to see arguments for. so i don't want to change the function name every time i need to do it. Commented Sep 10, 2020 at 4:09
  • Wouldn't a decorator be better then? And see xyproblem.info Commented Sep 10, 2020 at 9:10

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.