-1

I feel sure that I read about this somewhere but can't remember the details. The problem I have is this:

I have two functions

def go_foo():
    print("foo")

def go_bar():
    print("bar")

and this variable:

name = "foo"

I want to use name to call one of my functions like this:

go_{name}()

#output in this case would be foo

How can this be achieved?

Jessica Chambers
  • 1,246
  • 5
  • 28
  • 56
  • By using an [if](https://docs.python.org/3/tutorial/controlflow.html#if-statements) statement? – Stop harming Monica Sep 02 '19 at 12:49
  • @Goyo that is my current solution, I just wanted to know if there was a tighter way of coding the same thing – Jessica Chambers Sep 02 '19 at 12:50
  • Sure, look at the answers. Now imagine somebody else wrote the code and you never saw it until it is given to you to fix some bug or make some chage. Would you rather see tight code or code thar is explicit and easy to understand? – Stop harming Monica Sep 02 '19 at 12:58
  • @Goyo in my defense I literally had to do that on another project (hence where I heard about using variable values in function names like this) – Jessica Chambers Sep 02 '19 at 13:07

2 Answers2

2

you can also do it using locals()

Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.

def go_foo():
    print("foo")

def go_bar():
    print("bar")

name = "foo"

locals()['go_'+name]()
ncica
  • 7,015
  • 1
  • 15
  • 37
1
eval('go_'+name)()

Many will of course tell you that this is dangerous code, prone to code injection if the value of name variable could be altered. The more you ignore those people, the better off your are (normally). Especially as this normally is not done in a production environment.

Jonas Byström
  • 25,316
  • 23
  • 100
  • 147