How to call every function in an imported python module

故事扮演 提交于 2021-01-28 11:41:03

问题


I have a program that I wrote that is creating and maintaining an array and I have another module that I wrote that has functions to manipulate the array. Is it possible to call every function in the imported module without having to hard code every function call? Meaning something like this:

#Some way I don't know of to get a list of function objects
    listOfFunctions = module.getAllFunctions()

    for function in listOfFunctions:
        array.function()

I want to do this so I don't have to update my main file every time I add a function to my manipulation module.

I found these:

How to call a function from every module in a directory in Python?

Is it possible to list all functions in a module?

listing all functions in a python module

and also only found listing the functions in a module on the python docs. I can think of a way to do this using some string manipulation and the eval() function but I feel like there has to be a better, more pythonic way


回答1:


I think you want to do something like this:

import inspect

listOfFunctions = [func_name for func_name, func in module.__dict__.iteritems()\
                  if inspect.isfunction(func)]

for func_name in listOfFunctions:
    array_func = getattr(array, func_name)
    array_func()



回答2:


When you import a module, the __dict__ attribute contains all the things defined in the module (variables, classes, functions, etc.). You can iterate over it and test if the item is a function. This can for example be done by checking for a __call__ attribute:

listOfFunctions = [f for f in my_module.__dict__.values()
                   if hasattr(f,'__call__')]

Then, we can call each function in the list by invoking the __call__ attribute:

for f in listOfFunctions:
    f.__call__()

But be careful! There is no guaranteed order to the dictionary. The functions will be called in a somewhat random order. If order is important, you might want to use a naming scheme that enforces this order (fun01_do_something, fun02_do_something, etc.) and sort the keys of the dictionary first.



来源:https://stackoverflow.com/questions/28570715/how-to-call-every-function-in-an-imported-python-module

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