python - 从该函数中确定函数名称(不使用回溯)

标签 python function introspection traceback

在 Python 中,在不使用 traceback 模块的情况下,有没有办法从该函数中确定函数的名称?

假设我有一个带有函数 bar 的模块 foo。执行foo.bar()时,有没有办法让bar知道bar的名字?或者更好的是,foo.bar 的名字?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

最佳答案

import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3])  # will give the caller of foos name, if something called foo

foo()

输出:

foo
<module_caller_of_foo>

关于python - 从该函数中确定函数名称(不使用回溯),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067604/

相关文章:

python - 获取函数内部的 kwargs

python - Thead.join() 仅在所有线程完成后才帮助打印字符串

python - Python 3 的 WSGI 请求和响应包装器

python - Counter()+=Counter 和 Counter.update(Counter) 哪个更快?

laravel - DateTime::__construct(): 无法解析位置 0 (2) 处的时间字符串 (22/03/1983):意外字符

python - 包装使用 import * 导入的函数?

objective-c - 发送给对象的 className 和 isKindOfClass 消息

Python:如何在处理其他异常的同时忽略异常

python - 使用张量计算错误值的梯度下降

sql-server - 如果 SQL Server CASE 值为 NULL,则不返回任何内容