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 Bowen 404 for Calling a function of a module by using its name (a string)

$
0
0

i'm facing the similar problem before, which is to convert a string to a function. but i can't use eval() or ast.literal_eval(), because i don't want to execute this code immediately.

e.g. i have a string "foo.bar", and i want to assign it to x as a function name instead of a string, which means i can call the function by x()ON DEMAND.

here's my code:

str_to_convert = "foo.bar"exec(f"x = {str_to_convert}")x()

as for your question, you only need to add your module name foo and . before {} as follows:

str_to_convert = "bar"exec(f"x = foo.{str_to_convert}")x()

WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.


Viewing all articles
Browse latest Browse all 22

Trending Articles



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