I have a string which contains a python code. Is there a way to create a python module object using the string without an additional file?
content = "import math\n\ndef f(x):\n return math.log(x)"
my_module = needed_function(content) # <- ???
print my_module.f(2) # prints 0.6931471805599453
Please, don't suggest using eval or exec. I need a python module object exactly. Thanks!
You can create an empty modules with imp module then load your code in the module with exec.
content = "import math\n\ndef f(x):\n return math.log(x)"
import imp
my_module = imp.new_module('my_module')
exec content in my_module.__dict__ # in python 3, use exec() function
print my_module.f(2)
This is my answer, but I do not recommend using this in an actual application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With