【问题标题】:Python: how to get the *full* name of the function I am inPython:如何获取我所在函数的 *full* 名称
【发布时间】:2018-01-10 05:46:12
【问题描述】:

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

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

?

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

朱利安

编辑:

这里的重点是'log'函数能够检索它的调用者 单独命名(使用回溯、检查或任何必要的手段)。

我不想传递类名或“消息”以外的任何其他内容 到“日志”功能。

【问题讨论】:

  • 你能用__qualname__吗?
  • @mgilson 给出了问题中的 python2.x 语法,我猜不是?
  • @AnthonySottile -- 是的,我自己只是得出这个结论 -- 尽管 pypi (pypi.python.org/pypi/qualname) 上有一个(不完美的)替代品
  • @AnthonySottile -- 另外,从frame 对象,我认为您实际上没有对函数对象的引用 -- 只有它的名称。

标签: python traceback inspect


【解决方案1】:

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

#!/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__。

【讨论】:

    【解决方案2】:

    inspect 模块非常强大,可以像使用traceback 一样获取函数名,也可能是类名。但是您可以简单地利用您拥有 self 实例变量这一事实,它知道自己的类型/类:

    import inspect
    
    class cls(object):
        def f1(self):
            this_class_name = type(self).__name__
            this_func_name = inspect.currentframe().f_code.co_name
            print(this_class_name, this_func_name)
    
    mycls = cls()
    mycls.f1()
    

    【讨论】:

    • 你是对的。但是,我真正想要实现的目标(抱歉,我没有在我的问题中明确提出)是从回溯中检索类名,而无需将其作为参数传递给我的“日志”函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2023-03-27
    • 2011-01-10
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多