Python 是否可以列出模块中的所有功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4040620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to list all functions in a module?
提问by user478514
I defined a .py file in this format:
我以这种格式定义了一个 .py 文件:
foo.py
文件
def foo1(): pass
def foo2(): pass
def foo3(): pass
I import it from another file:
我从另一个文件导入它:
main.py
主文件
from foo import *
# or
import foo
Is it possible list all functions name, e.g. ["foo1", "foo2", "foo3"]?
是否可以列出所有函数名称,例如["foo1", "foo2", "foo3"]?
Thanks for your help, I made a class for what I want, pls comment if you have suggestion
感谢您的帮助,我做了一个我想要的课程,如果您有建议,请发表评论
class GetFuncViaStr(object):
def __init__(self):
d = {}
import foo
for y in [getattr(foo, x) for x in dir(foo)]:
if callable(y):
d[y.__name__] = y
def __getattr__(self, val) :
if not val in self.d :
raise NotImplementedError
else:
return d[val]
采纳答案by aaronasterling
The cleanest way to do these things is to use the inspect module. It has a getmembersfunction that takes a predicate as the second argument. You can use isfunctionas the predicate.
做这些事情的最干净的方法是使用检查模块。它有一个getmembers将谓词作为第二个参数的函数。您可以isfunction用作谓词。
import inspect
all_functions = inspect.getmembers(module, inspect.isfunction)
Now, all_functionswill be a list of tuples where the first element is the name of the function and the second element is the function itself.
现在,all_functions将是一个元组列表,其中第一个元素是函数的名称,第二个元素是函数本身。
回答by pyfunc
you can use dir to explore a namespace.
您可以使用 dir 来探索命名空间。
import foo
print dir(foo)
Example: loading your foo in shell
示例:在 shell 中加载你的 foo
>>> import foo
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo1', 'foo2', 'foo3']
>>>
>>> getattr(foo, 'foo1')
<function foo1 at 0x100430410>
>>> k = getattr(foo, 'foo1')
>>> k.__name__
'foo1'
>>> callable(k)
True
>>>
You can use getattr to get the associated attribute in foo and find out if it callable.
您可以使用 getattr 获取 foo 中的关联属性并确定它是否可调用。
Check the documentation : http://docs.python.org/tutorial/modules.html#the-dir-function
检查文档:http: //docs.python.org/tutorial/modules.html#the-dir-function
and if you do - "from foo import *" then the names are included in the namespace where you call this.
如果您这样做了 - “from foo import *” 那么名称将包含在您调用它的名称空间中。
>>> from foo import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'atexit', 'foo1', 'foo2', 'foo3']
>>>
The following brief on introspection in python might help you :
以下有关 Python 内省的简介可能会对您有所帮助:
回答by AndiDog
For a wild import
对于野生进口
from foo import *
print dir()
you can use dir()without a parameter to show objects in the current module's namespace. This will most probably include more than just the content of foo.
您可以dir()不带参数使用来显示当前模块命名空间中的对象。这很可能不仅包括foo.
In case of an absolute import (which you should prefer by the way) you can pass the module to dir():
如果是绝对导入(顺便说一下,您应该更喜欢),您可以将模块传递给dir():
import foo
print dir(foo)
Also check the documentation of dir. As you only wanted functions, you might want to think about using inspect.isfunction. Hope you don't use that list for non-debugging purposes.
另外,还要检查的文件dir。由于您只需要函数,因此您可能需要考虑使用inspect.isfunction. 希望您不要将该列表用于非调试目的。
回答by shahjapan
Try using inspect module like below for exmaple if module --> temp.py
尝试使用像下面这样的检查模块作为例子 if module --> temp.py
In [26]: import inspect
In [27]: import temp
In [28]: l1 = [x.__name__ for x in temp.__dict__.values() if inspect.isfunction(x)]
In [29]: print l1
['foo', 'coo']
回答by Flimm
Like
aaronasterling said, you can use the getmembersfunctions from the inspectmodule to do this.
就像
aaronasterling 所说的,您可以使用模块中的getmembers函数inspect来执行此操作。
import inspect
name_func_tuples = inspect.getmembers(module, inspect.isfunction)
functions = dict(name_func_tuples)
However, this will include functions that have been defined elsewhere, but imported into that module's namespace.
但是,这将包括已在别处定义但导入到该模块的命名空间中的函数。
If you want to get only the functions that have been defined in that module, use this snippet:
如果您只想获取已在该模块中定义的函数,请使用以下代码段:
name_func_tuples = inspect.getmembers(module, inspect.isfunction)
name_func_tuples = [t for t in name_func_tuples if inspect.getmodule(t[1]) == module]
functions = dict(name_func_tuples)
回答by verboze
if wanting to list functions of the current module (i.e., not an imported one), you could also do something like this:
如果要列出当前模块的功能(即,不是导入的),您还可以执行以下操作:
import sys
def func1(): pass
def func2(): pass
if __name__ == '__main__':
print dir(sys.modules[__name__])

