是否可以列出模块中的所有功能?

发布于 2024-09-29 06:44:27 字数 708 浏览 7 评论 0原文

我以这种格式定义了一个 .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] 

I defined a .py file in this format:

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"]?


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] 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

待"谢繁草 2024-10-06 06:44:28

对于狂野导入,

from foo import * 
print dir()

您可以使用不带参数的 dir() 来显示当前模块名称空间中的对象。这很可能不仅仅包括 foo 的内容。

如果是绝对导入(顺便说一下,您应该更喜欢这种方式),您可以将模块传递给 dir()

import foo
print dir(foo)

另请检查 dir 的文档。由于您只需要函数,因此您可能需要考虑使用 inspect.isfunction。希望您不要将该列表用于非调试目的。

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.

In case of an absolute import (which you should prefer by the way) you can pass the module to 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.

心碎无痕… 2024-10-06 06:44:28

如果想列出当前模块的函数(即不是导入的函数),你也可以这样做:

import sys
def func1(): pass
def func2(): pass

if __name__ == '__main__':
    print dir(sys.modules[__name__])

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__])
她如夕阳 2024-10-06 06:44:27

执行这些操作的最简洁方法是使用检查模块。它有一个 getmembers 函数,该函数将谓词作为第二个参数。您可以使用 isfunction 作为谓词。

 import inspect

 all_functions = inspect.getmembers(module, inspect.isfunction)

现在,all_functions 将是一个元组列表,其中第一个元素是函数的名称,第二个元素是函数本身。

The cleanest way to do these things is to use the inspect module. It has a getmembers function that takes a predicate as the second argument. You can use isfunction as the predicate.

 import inspect

 all_functions = inspect.getmembers(module, inspect.isfunction)

Now, all_functions will be a list of tuples where the first element is the name of the function and the second element is the function itself.

若水微香 2024-10-06 06:44:27

您可以使用 dir 来探索名称空间。

import foo
print dir(foo)

示例:在 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
>>> 

您可以使用 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 内省的简介可能会对您有所帮助:

you can use dir to explore a namespace.

import foo
print dir(foo)

Example: loading your foo in shell

>>> 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.

Check the documentation : 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 *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'atexit', 'foo1', 'foo2', 'foo3']
>>> 

The following brief on introspection in python might help you :

你没皮卡萌 2024-10-06 06:44:27

喜欢
aaronasterling 说,你可以使用getmembers 来自 inspect 模块的函数来执行此操作。

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)

Like
aaronasterling said, you can use the getmembers functions from the inspect module to do this.

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)
离线来电— 2024-10-06 06:44:27

尝试使用检查模块,如下所示,例如 if module -->温度.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']

Try using inspect module like below for exmaple 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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文