-2
# funcs.py
def foo():
    print('invoked')

# main.py
import funcs
name = 'foo'
funcs.name()  # doesn't work

How to invoke a function that is dynamically selected and the name is stored in a string?

Vorac
  • 8,726
  • 11
  • 58
  • 101

1 Answers1

0

Use

eval(name + "()")

Like This

#funcs
def foo():
    print('invoked')

# main.py
from funcs import foo
name = 'foo'
eval(name + "()")
  • 1
    Thanks for the answer! But it seems less safe than the highly upvoted `getattr(module, funcname)()`. I mean I kind of trust my input strings but an `eval()` is too allmighty. – Vorac Jan 08 '22 at 19:05