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

后端 未结 5 1355
一向
一向 2020-11-29 23:06

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

5条回答
  •  孤城傲影
    2020-11-29 23:51

    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.

提交回复
热议问题