2

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!

1
  • I just wonder why you'd need a real separate module for that. Commented Sep 11, 2015 at 14:06

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct answer. Of course, you should never ever do this.
just learned about exec .. in .., "nice"
how would you do it now, once imp module is deprecated and up for removal in 3.12?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.