likes
comments
collection
share

python:打印方法名称

作者站长头像
站长
· 阅读数 3

前言

之前写了一个python的内部工具,使用PyCharm作为IDE。调试时需要打印出重要方法的名称,便于从Log中查找分析问题。 一开始就是直接将名称打印出来

def foo():
    print("调用了 foo")

打印为

调用了 foo

简简单单,没多大问题。 直到后面修改了这个方法的名称之后...发现打印出来的名称并没有随着修改,还要自己手动修改,麻烦。

使用sys模块获取方法名称

一顿百度之后,大多都是推荐使用sys模块来获取python的方法名称。

 import sys
 def foo():
     print("调用了 %s" % sys._getframe().f_code.co_name)

运行后打印出来没有问题,而且修改方法名后会自动跟随着改变。 看起来没问题了,但是IDE会显示一个警告,Access to a protected member _getframe of a module,强迫症表示看起来很难受。

python:打印方法名称 这个原因是sys._getframe()是一个受保护的方法,不建议在外部调用,但实际调用了也能正常运行。 除此之外,这个方法在编写的时候是没有提示的,也无法点进去查看定义。强行查看定义会报错Cannot find declaration to go to

python:打印方法名称 查看Python的相关文档

  • sys._getframe([depth])

  • Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.

    Raises an auditing event sys._getframe with no arguments.

    CPython implementation detail:  This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.

关注最后一句,

sys._getframe()函数应仅用于内部和专用目的。它不能保证存在于 Python 的所有实现中。

也就是说官方本身并不推荐我们使用sys._getframe方法,在某些版本里面这个方法可能不存在。

使用inspect模块获取方法名称

既然sys._getframe()的方案不好用,那么就尝试换一种方式。一波Google之后终于找到了。可以使用inspect模块要获取方法名称。

import inspect
def foo():
    print("调用了 %s" % inspect.currentframe().f_code.co_name)

这个方法不会有警告,也可以正常点进去看方法的定义,完美。

使用__name__在方法外部获取方法名称

我们之前是在方法内部获取的方法名称,有时候需要在方法外部获取方法名称,一般建议使用__name__.

print("方法名为:%s" % foo.__name__)

打印结果

方法名为:foo

总结

Python方法内部获取方法名称,建议使用inspect.currentframe().f_code.co_name),不建议使用sys._getframe().f_code.co_name)以及直接硬编码。 Python外部获取方法名称,建议使用方法名.__name__

参考

How to get a function name as a string? Python doc sys