0

So what I'm trying to do is run a function using concatenation like this:

location = 1
"critter_" + location + "()"

and I was hoping that would run the function 'critter_1()' but apparently it doesn't work like that so I tried a couple of stuff since it gave me an error about str to int concatenation error. So what I tried was:

location = 1
"critter_" + int(location) + "()"

And it still didn't work so I came here to ask you guys if there is any way to actually do this.

Any ideas? Thanks!

RepeaterCreeper
  • 342
  • 3
  • 23

2 Answers2

2

You can use globals()[function_name] to get function object. Once you get the function object, call it like ordinary name.

func = globals()['critter_{}'.format(location)]
# OR  func = globals()['critter_' + str(location)]
func()
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

You have two separate problems:

  1. You need to get the correct name for the function, so you need to convert your integer 1 to the string '1'. The easiest way is to just use funcname = "critter_"+str(location), although you have more control over the way the conversion is done if you use the format method of the strings. (You've got the meaning of int almost exactly backwards -- it converts to an integer; str converts to a string!)

  2. You need to call the function given by the string. For this, you can use a number of different methods. Simplest is probably just to call eval(funcname+"()"), although this isn't always safe. You can also use funcname to find the function in the dictionary which stores all globally defined function, globals()[funcname].

Alternately, you could make your own list or dictionary of critter_n functions, and select from that:

critter_functions = {1: critter_1, 2: critter_2} #etc...
# ...

location = 1
critter_functions[location]()
Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59