我的系统中安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。
我想在每个模块上调用文档函数。在Ruby中,我可以做一些类似ClassName.methods的事情来获得该类所有可用方法的列表。在python中是否有类似的东西?
例如,类似的东西。
from somemodule import foo
print foo.methods # or whatever is the correct method to call
为了完整性'。
的缘故,我'想指出,有时你可能想要_解析代码,而不是导入它。
import
会执行顶层表达式,这可能是个问题。
例如,我让用户为使用[zipapp][1]制作的包选择入口点函数。 使用 "import "和 "inspect "有可能跑错代码,导致崩溃,帮助信息被打印出来,GUI对话框弹出等等。
相反,我使用[ast][2]模块来列出所有的顶层函数。
import ast
import sys
def top_level_functions(body):
return (f for f in body if isinstance(f, ast.FunctionDef))
def parse_ast(filename):
with open(filename, "rt") as file:
return ast.parse(file.read(), filename=filename)
if __name__ == "__main__":
for filename in sys.argv[1:]:
print(filename)
tree = parse_ast(filename)
for func in top_level_functions(tree.body):
print(" %s" % func.name)
将这段代码放在list.py
中,并将其本身作为输入,我得到了。
$ python list.py list.py
list.py
top_level_functions
parse_ast
当然,即使对于像Python这样相对简单的语言来说,浏览AST有时也是很棘手的,因为AST是相当低级的。 但是,如果你有一个简单而明确的用例,它既可行又安全。
虽然,一个缺点是你不能检测到在运行时生成的函数,比如foo = lambda x,y: x*y
.
[1]: https://docs.python.org/dev/library/zipapp.html [2]: https://docs.python.org/3.2/library/ast.html#module-ast
dir(module)
是使用脚本或标准解释器时的标准方法,正如大多数答案中提到的那样。
然而,如果使用像IPython这样的交互式python shell,你可以使用tab-completion来获得模块中定义的所有对象的概览。 这比使用脚本和 "print "来查看模块中定义的内容要方便得多。
module.<tab>
将显示模块中定义的所有对象(函数、类等)。module.ClassX.<tab>
将向你展示一个类的方法和属性。module.function_xy?
或module.ClassX.method_xy?
将显示该函数/方法的docstring。module.function_x??
或module.SomeClass.method_xy??
将显示该函数/方法的源代码。对于全局函数来说,dir()
是要使用的命令(在大多数答案中都提到了),然而这将公共函数和非公共函数一起列出。
例如,运行
>>> import re
>>> dir(re)
返回函数/类,如:{{{5337016}}。
'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'
其中一些通常不是为了一般的编程使用 (而是由模块本身使用,除了像 __doc__
, __file__
等 DunderAliases)。
出于这个原因,把它们和公共的一起列出可能没有什么用 (当使用 "from module import *"时,Python 就是这样知道要得到什么)。
__all__
可以用来解决这个问题,它返回一个模块中所有公共函数和类的列表 (那些 * 不以下划线开头的函数 - _
)。
参见
https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python,以便使用"__all__"。
下面是一个例子。
>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>
所有带下划线的函数和类都被删除了,只留下那些被定义为公共的函数和类,因此可以通过import *
使用。
请注意,__all__
并不总是被定义。
如果它没有被包含,那么就会引发AttributeError
。
ast模块就是一个例子。
>>> import ast
>>> ast.__all__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>
如果你无法导入上述Python文件而不出现导入错误,这些答案都是行不通的。 当我在检查一个文件时就遇到了这种情况,这个文件来自于一个有很多依赖关系的大型代码库。 下面将把文件作为文本处理,搜索所有以"def".开头的方法名,并打印它们和它们的行号。 开头的方法名,并打印它们和它们的行号。
import re
pattern = re.compile("def (.*)\(")
for i, line in enumerate(open('Example.py')):
for match in re.finditer(pattern, line):
print '%s: %s' % (i+1, match.groups()[0])
除了前面答案中提到的dir(模块)或help(模块),你还可以尝试:<br>。
下面是列出hashlib模块所有函数的片段。
(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import hashlib
In [2]: hashlib.
hashlib.algorithms hashlib.new hashlib.sha256
hashlib.algorithms_available hashlib.pbkdf2_hmac hashlib.sha384
hashlib.algorithms_guaranteed hashlib.sha1 hashlib.sha512
hashlib.md5 hashlib.sha224
这将把所有定义在 your_module 中的函数附加到一个列表中。
result=[]
for i in dir(unit8_conversion_methods):
if type(getattr(your_module, i)).__name__ == "function":
result.append(getattr(your_module, i))