Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of a function or method from within a Python function or method?

Tags:

python

I feel like I should know this, but I haven't been able to figure it out...

I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

like image 414
Daryl Spitzer Avatar asked Oct 28 '08 23:10

Daryl Spitzer


People also ask

How do I get the details of a function in Python?

Python help() function is used to get the documentation of specified module, class, function, variables etc. This method is generally used with python interpreter console to get details about python objects.

Can a function be called from within a function in Python?

In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.

How do you read a function name in Python?

Method 1: Get Function Name in Python using function. func_name. By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy for the Testing purpose and also for documentation at times.


1 Answers

This seems to be the simplest way using module inspect:

import inspect def somefunc(a,b,c):     print "My name is: %s" % inspect.stack()[0][3] 

You could generalise this with:

def funcname():     return inspect.stack()[1][3]  def somefunc(a,b,c):     print "My name is: %s" % funcname() 

Credit to Stefaan Lippens which was found via google.

like image 188
mhawke Avatar answered Oct 05 '22 22:10

mhawke