I have a string stored in a database stands for a class instance creation for example module1.CustomHandler(filename="abc.csv", mode="rb")
, where CustomHandler is a class defined in module1.
I would like to evaluate this string to create a class instance for a one time use. Right now I am using something like this
statement = r'module1.CustomHandler(filename="abc.csv", mode="rb")' # actually read from db
exec(f'from parent.module import {statement.split(".")[0]}')
func_or_instance = eval(statement) # this is what I need
Only knowledgable developers can insert such records into database so I am not worried about eval
some unwanted codes. But I've read several posts saying eval
is unsafe and there is always a better way. Is there a way I can achieve this without using eval
?