Is it possible to list all functions in a module? [duplicate]

巧了我就是萌 提交于 2019-11-26 19:35:09

问题


This question already has an answer here:

  • How to list all functions in a Python module? 14 answers

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] 

回答1:


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.




回答2:


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 :

  • http://www.ibm.com/developerworks/library/l-pyint.html



回答3:


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']



回答4:


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)



回答5:


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__])



回答6:


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.



来源:https://stackoverflow.com/questions/4040620/is-it-possible-to-list-all-functions-in-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!