I have a module, in the module is a subcomponent which contains a multitude of functions. I need to iterate through a list of names which contains the names of the modules and call the functions. this does not work, "because module has no attribute list". How do I make list[x] callable as a subcomponent of module instead of "list" the name.
file 1:
def x():
print('x')
def y():
print('y')
def z():
print('z')
file 2:
import module # containing functions x(),y(),z()
list = ['x','y','z']
for x in list:
module.list[x]()
Try getattr()
:
import module
lst = ["x", "y", "z"]
for item in lst:
getattr(module, item)()
Prints:
<function x at 0x7f2c56129e50>
<function y at 0x7f2c56129f70>
<function z at 0x7f2c560e4c10>
You can use getattr
to access to the "content" of the module.
Using dir
to "introspect" the content of the module:
import my_module
func_names = ['x','y','z']
callable_funcs = []
for stuffs in dir(my_module):
if stuff in func_names:
callable_funcs.append(getattr(my_module, stuff))
# make a dictionary
funcs = dict(zip(func_names, callable_funcs))
# usage
x = funcs['x']
print(x())
Another way using getattr
and hasattr
:
import my_module
func_names = ['x','y','z']
callable_funcs = []
for f_name in func_names:
if hasattr(my_module, f_name):
callable_funcs.append(getattr(my_module, f_name))
# make a dictionary
funcs = dict(zip(func_names, callable_funcs))
# usage
x = funcs['x']
print(x())
It can be done also using a dictionary comprehension:
import my_module
func_names = ['x','y','z']
funcs = {f_name: getattr(my_module, f_name) for f_name in func_names if hasattr(my_module, f_name)}
Why don't you just store the functions in the list?
>>> def x():
... print("x")
...
>>> def y():
... print("y")
...
>>> functions = [x, y]
>>> for f in functions:
... f()
...
x
y
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.