从该函数内确定函数名称(不使用回溯) [英] Determine function name from within that function (without using traceback)

查看:32
本文介绍了从该函数内确定函数名称(不使用回溯)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,不使用 traceback 模块,有没有办法从函数内部确定函数的名称?

In Python, without using the traceback module, is there a way to determine a function's name from within that function?

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

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name?

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

推荐答案

Python 没有在函数本身内访问函数或其名称的功能.它已被提议但被拒绝.如果您不想自己玩堆栈,则应根据上下文使用 "bar"bar.__name__.

Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context.

给出的拒绝通知是:

此 PEP 被拒绝.目前尚不清楚它应该如何实现,或者在边缘情况下精确的语义应该是什么,并且没有给出足够多的重要用例.反应充其量是不冷不热的.

This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.

这篇关于从该函数内确定函数名称(不使用回溯)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆