Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a module object by content in Python [duplicate]

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!

like image 787
Fomalhaut Avatar asked Dec 18 '25 04:12

Fomalhaut


1 Answers

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.

like image 198
wap26 Avatar answered Dec 20 '25 17:12

wap26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!