Home > Enterprise >  For loop through class
For loop through class

Time:02-24

import v1.bot.main
import v2.bot.main

for i in ['v1', 'v2]:
    # I want the for loop to do something like i.bot.main()
    
    # Like
    # v1.bot.main()
    # v2.bot.main()

Is this possible? I want to get rid of the writing of vX and want to put it into a for loop.

CodePudding user response:

as keyword is important because import statement returns an object of type <class 'module'>. You'll be calling the main() function through the module object.

import v1.bot.main as v1
import v2.bot.main as v2

for i in ["v1", "v2"]:
    eval(f"{i}.main()")

CodePudding user response:

The easiest way to do this would be to add all the version instances of bot to a dictionary like:

global_bot_list = {1 : v1.bot(), 2: v2.bot()}

Then just do a for loop like this:

for bot in global_bot_list.items():
     bot.main()

If you want to make code completion work you should probably make an abstract base class for all your bots to inherit from that has the main method and change the signature of global_bot_list to: global_bot_list: Dict[int, BotBase] with BotBase being whatever name you chose to call the new base class.

By the way in order for this to work you will need to add an __init__ method to each bot class and main needs to be an instance method that has self as its first parameter.

  • Related