【问题标题】:__PRETTY_FUNCTION equivalent in PythonPython 中的 __PRETTY_FUNCTION 等价物
【发布时间】:2020-06-01 01:02:10
【问题描述】:

g++ 有一个很好的变量PRETTY_FUNCTION,它包含被调用函数的名称。对于函数,它会生成原型(例如,“void foo(long)”)。对于类中的成员函数,名称包括类名(例如,“void Foo::foo(long)”)。

在 Python 中是否有等价物。我一直在玩“sys._getframe()”,它很接近,但似乎没有一个类似的简单机制,当它是成员函数时包含类名。 p>

我喜欢在错误处理程序中使用它。

肯定有人对此有一个神奇的单线......

TIA,

-乔

【问题讨论】:

标签: python-3.x


【解决方案1】:

Example Python Code

这是我现在能得到的最接近的值。搜索“

键入 Foo.CLNAME 有点傻。如果它可以以某种方式折叠到外部函数并留在类之外,那就太好了。必须有一种方法可以在 Python 中以类似于 LINENAME 工作方式的方式执行此操作。

这两个的实现是基于我从这里得到的代码:

How to determine file, function and line number?

好东西!

-乔

=====

#!/usr/bin/env python

# import system modules
#
import os
import sys

# define a hack to get the function name
#                                                                             
class __MYNAME__(object):
    def __repr__(self):
        try:
            raise Exception
    except:
        return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)

    def __init__(self):
        pass

__NAME__ = __MYNAME__()

# define a hack to get the line number in a program                            
#                                                                             
class __MYLINE__(object):
    def __repr__(self):
        try:
            raise Exception
        except:
            return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)

__LINE__ = __MYLINE__()

# use these in a function call
#
def joe():
    print("[FUNCTION] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

# use these in a class member function
#
class Foo():

    def __init__(self):
        Foo.__CLNAME__ = self.__class__.__name__

    def joe(self):
        print("[CLASS] name: %s::%s, line: %s" %
              (Foo.__CLNAME__, __NAME__, __LINE__))  # <<< here

#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):

    # main program
    #
    print("[MAIN PROGRAM] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

    # function call
    #
    joe()

    # class member function
    #
    foo = Foo()
    foo.joe()

    # exit gracefully
    #
    sys.exit(os.EX_OK)

#
# end of main

# begin gracefully
#
if __name__ == "__main__":
    main(sys.argv[0:])

#
# end of file

【讨论】:

    猜你喜欢
    • 2018-09-06
    • 2013-02-06
    • 2012-03-22
    • 2016-12-27
    • 2013-12-13
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多