0

Possible Duplicate:
How to dynamically load a Python class

I'm currently using a 'while' loop to automate the process of updating games stored in a database. The 'while' loop iterates until the number of games has been reached. Each iteration returns the row containing all game data (version, update link, etc).

Now I've created scripts for each game in a sub-directory called "Scripts". Like this

MainScript.py
  --> Scripts
       --> Game1.py
       --> Game2.py
       --> Game3.py

Now MainScript calls all the game scripts one by one, after connecting to the database and getting the game names.

But the problem is the game name stored in the database is a string and the functions in each of the Game1.py, Game2.py, Game3.py are identical to the game name.

This means that when I try call a function for the game, lets say "Minecraft". It would have to look like this.

Scripts.Minecraft.Minecraft(version, size, download)

Now trying to do this dynamically is my question. Because it's in a while loop, the name part changes for each iteration. How do I do this dynamically?

Scripts.<GameName>.<GameName>(version, size, download)

It always takes the variable literally and says it cannot use it. How do I use variables when calling the function?

Community
  • 1
  • 1
Skowt
  • 411
  • 2
  • 6
  • 15

1 Answers1

3

Try using getattr. E.g. given the the game name is in the gamename variable:

getattr(getattr(Scripts, gamename), gamename)(version, size, download)

should work.

Michael
  • 8,920
  • 3
  • 38
  • 56
  • This finally solved the problem. I got as far as getattr before but the nested getattr is where I stumbled. Thanks Michael! :D – Skowt Jan 27 '13 at 13:19