Zanam
Zanam

Reputation: 4807

Getting function name while debugging

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

Upvotes: 0

Views: 75

Answers (1)

Xiddoc
Xiddoc

Reputation: 3638

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

Upvotes: 1

Related Questions