是否可以列出模块中的所有函数?
我定义了一个.py文件,格式如下:
foo.py
def foo1(): pass
def foo2(): pass
def foo3(): pass
我从另一个文件中导入它:
main.py
from foo import *
# or
import foo
有没有办法列出所有函数的名字,比如 ["foo1", "foo2", "foo3"]
?
谢谢你的帮助,我为我想要的内容做了一个类,如果你有建议请评论。
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]
6 个回答
8
就像aaronasterling说的,你可以使用inspect
模块里的getmembers
函数来实现这个功能。
import inspect
name_func_tuples = inspect.getmembers(module, inspect.isfunction)
functions = dict(name_func_tuples)
不过,这样做会包括那些在其他地方定义的函数,但被导入到这个模块的命名空间里。
如果你只想获取在这个模块中定义的函数,可以使用下面这段代码:
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)
10
你可以用 dir 来查看一个命名空间里的内容。
import foo
print dir(foo)
举个例子:在命令行中加载你的 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
>>>
你可以用 getattr 来获取 foo 里的某个属性,看看它是否可以被调用。
查看文档了解更多信息: http://docs.python.org/tutorial/modules.html#the-dir-function
如果你使用了 "from foo import *",那么这些名字就会被包含在你调用这个的命名空间里。
>>> from foo import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'atexit', 'foo1', 'foo2', 'foo3']
>>>
下面这段关于 Python 中自省的简要说明可能对你有帮助:
81
做这些事情最简单的方法是使用inspect模块。这个模块里有一个叫getmembers
的函数,它的第二个参数可以用来指定条件。你可以用isfunction
作为这个条件。
import inspect
all_functions = inspect.getmembers(module, inspect.isfunction)
现在,all_functions
将会是一个包含多个元组的列表,每个元组的第一个元素是函数的名字,第二个元素是这个函数本身。