0

I have this simple function:

def fu():
    return "great"

I need to call it by using a string,

So I tried this:

print(exec("fu()"))

But the the output I got was:

None

How do i fix it?

Mehrdad Pedramfar
  • 9,989
  • 4
  • 33
  • 55
raz erez
  • 79
  • 2
  • 11
  • 3
    exec ignores the return value of a function, and always returns `None`, which is why none is printed. – user3483203 May 12 '18 at 14:32
  • There are quite a few smilar, maybe this one is closer: [Use a string to call function in Python](https://stackoverflow.com/q/4131864/2823755) – wwii May 12 '18 at 14:56

1 Answers1

0

As in comments says you can not use exec for this purpose.
but eval will do what you want, full doc here:

>> eval('fu()')
"great"

Note that using eval is not the best practice.

There is a better way to access this function with globals or locals based on where you define your function, and I think it's better to use this instead of eval:

>> globals()['fu']()
"great"
Mehrdad Pedramfar
  • 9,989
  • 4
  • 33
  • 55