0

I am trying the following code:

import inspect
def fn1(x):
 print(1*x)
 print(inspect.stack()[0][4]) #print fn1

def fn2(x):
 print(2*x*x)
 print(inspect.stack()[0][4]) #print fn2

def fn3(x):
 print(3*x*x*x)
 print(inspect.stack()[0][4]) #print fn3

class printFuncName():
 def __init__(fn):
    self.fn = fn
    self.fn(12)

if __name__ == '__main__':
   funcs = [fn1, fn2, fn3]    
   for ii in funcs:
     printFuncName(ii)
  

But the print(inspect.stack()[0][4]) doesn't print the name of function. It prints ''.

I was expecting it to print 'fn1', 'fn2', 'fn3'

Edit: Sorry seems like it was answered while I was editing the question

1 Answer 1

1

You could instead access the function attribute directly:

import inspect

def fn1(x):
 print(1*x)
 print(inspect.stack()[0].function)

def fn2(x):
 print(2*x*x)
 print(inspect.stack()[0].function)

def fn3(x):
 print(3*x*x*x)
 print(inspect.stack()[0].function)

funcs = [fn1, fn2, fn3]

for ii in funcs:
  ii(12)

Outputs:

12
fn1
288
fn2
5184
fn3
Sign up to request clarification or add additional context in comments.

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.