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

后端 未结 5 1360
一向
一向 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:44

    This decorator makes the name of the method available inside the function by passing it as a keyword argument.

    from functools import wraps
    def pass_func_name(func):
        "Name of decorated function will be passed as keyword arg _func_name"
        @wraps(func)
        def _pass_name(*args, **kwds):
            kwds['_func_name'] = func.func_name
            return func(*args, **kwds)
        return _pass_name
    

    You would use it this way:

    @pass_func_name
    def sum(a, b, _func_name):
        print "running function %s" % _func_name
        return a + b
    
    print sum(2, 4)
    

    But maybe you'd want to write what you want directly inside the decorator itself. Then the code is an example of a way to get the function name in a decorator. If you give more details about what you want to do in the function, that requires the name, maybe I can suggest something else.

提交回复
热议问题