How can get current function name inside that function in python

一笑奈何 提交于 2019-12-03 09:19:28

问题


For my logging purpose i want to log all the names of functions where my code is going

Does not matter who is calling the function , i want the the function name in which i declare this line

import inspect

def whoami():
    return inspect.stack()[1][3]

def foo():
    print(whoami())

currently it prints foo , i want to print whoami


回答1:


You probably want inspect.getframeinfo(frame).function:

import inspect

def whoami(): 
    frame = inspect.currentframe()
    return inspect.getframeinfo(frame).function

def foo():
    print(whoami())

foo()

prints

whoami



回答2:


For my logging purpose i want to log all the names of functions where my code is going

Have you considered decorators?

import functools
def logme(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        print(f.__name__)
        return f(*args, **kwargs)
    return wrapped


@logme
def myfunction();
    print("Doing some stuff")



回答3:


Actually, Eric's answer points the way if this is about logging:

For my logging purpose i want to log all the names of functions where my code is going

You can adjust the formatter to log the function name:

import logging               

def whoami():
    logging.info("Now I'm there")

def foo():
    logging.info("I'm here")
    whoami()
    logging.info("I'm back here again")

logging.basicConfig(
    format="%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s",
    level=logging.INFO)
foo()

prints

2015-10-16 16:29:34,227 [INFO] foo: I'm here
2015-10-16 16:29:34,227 [INFO] whoami: Now I'm there
2015-10-16 16:29:34,227 [INFO] foo: I'm back here again



回答4:


Use f_code.co_name member of the stack frame returned by sys._getframe().

sys._getframe(0).f_code.co_name

For example, in a whoami() function,

import sys

def whoami(): 
    return sys._getframe(1).f_code.co_name

def func1():
    print(whoami())

func1()  # prints 'func1'


来源:https://stackoverflow.com/questions/33162319/how-can-get-current-function-name-inside-that-function-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!