Quantcast
Channel: Calling a function of a module by using its name (a string) - Stack Overflow
Viewing all articles
Browse latest Browse all 22

Answer by Daniel Viglione for Calling a function of a module by using its name (a string)

$
0
0

Verified and tested:

# demo.pyimport sysdef f1():    print("Function 1 called")def f2():    print("Function 2 called")def f3():    print("Function 3 called")def f4():    print("Function 4 called")functions = {"f1": __name__,"f2": __name__,"f3": __name__,"f4": __name__}function_name = input("Enter the name of the function you want to call: ")try:    func = getattr(sys.modules[functions[function_name]], function_name)except Exception as e:    print(f"Error: {e}")else:    func()

Test:

% python3 demo.pyEnter the name of the function you want to call: f1Function 1 called

Viewing all articles
Browse latest Browse all 22

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>