首页 > 解决方案 > Python 中的 __PRETTY_FUNCTION 等价物

问题描述

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

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

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

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

TIA,

-乔

标签: python-3.x

解决方案


示例 Python 代码

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

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

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

如何确定文件、函数和行号?

好东西!

-乔

=====

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

推荐阅读