PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How do you call a function of a module in Python if the module should be called with a list or variable?

 August 24, 2022     for-loop, list, loops, module, python     No comments   

Issue

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

Solution

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>


Answered By - Andrej Kesely
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing