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.