1

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!

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95

1 Answers1

8

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.

wap26
  • 2,180
  • 1
  • 17
  • 32