gpt4 book ai didi

Python:如何获取我所在函数的*完整*名称

转载 作者:太空狗 更新时间:2023-10-30 00:19:55 30 4
gpt4 key购买 nike

有没有办法让下面的代码:

import traceback

def log(message):
print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message)

def f1():
log("hello")

class cls(object):
def f1(self):
log("hi there")

f1()
mycls = cls()
mycls.f1()

显示:

f1: hello
cls.f1: hi there

代替:

f1: hello
f1: hi there

?

我尝试使用模块“检查”但没有成功...

朱利安

EDIT:

The point here is for 'log' function to be able to retrieve its caller name on its own (using traceback, inspect, or any mean necessary).

I do not want to pass the class name, or anything else than 'message' to the 'log' function.

最佳答案

所以我终于想出了这个方法:

#!/usr/bin/env python3

def log(message):
import inspect
import gc
code = inspect.currentframe().f_back.f_code
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0]
print(func.__qualname__, message)

它需要 python3 以便可以使用 __qualname__。

关于Python:如何获取我所在函数的*完整*名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45470346/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com