Ege Eren
Ege Eren

Reputation: 7

How can i call function with string value that equals to function name

I'm trying to call myFunc() but i want to use a string value that equals to "myFunc" instead of typing by hand while calling it.

Here is some example that im trying to do;

a = "myFunc"

def myFunc():
   print("Bla bla")

a() ### How can i compile this code like its myFunc()


Upvotes: 0

Views: 447

Answers (3)

oppressionslayer
oppressionslayer

Reputation: 7224

Yes, you can call it with eval like this:

a = "myFunc()" 

def myFunc(): 
print("Bla bla") 

eval(a)                                                                                                                                             
Bla bla  

Does this help? Thanks! Eval is useful for calling functions in a list for example, you can iterate a list of functions like:

for item in functionlist:
  eval(item)

Upvotes: 0

Osman Mamun
Osman Mamun

Reputation: 2882

I can think of two ways you can do it:

Using global namespace

In [1]: def myfunc():
...:     print('Bla bla!') 
In [2]: a = 'myfunc'
In [3]: globals()[a]()
Bla bla! 

Or using eval

In [4]: eval(a + '()')
Bla bla!

Upvotes: 0

Samwise
Samwise

Reputation: 71562

In your example myFunc is a global variable, so:

globals()[a]()

If you look at the dict returned by globals() you'll see (among other items):

{'a': 'myFunc', 'myFunc': <function myFunc at 0x0119B618>}

Upvotes: 2

Related Questions