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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With