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?

2
  • 3
    exec ignores the return value of a function, and always returns None, which is why none is printed. Commented May 12, 2018 at 14:32
  • There are quite a few smilar, maybe this one is closer: Use a string to call function in Python Commented May 12, 2018 at 14:56

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.