Load module from string in python
<p>I have some code in the form of a string and would like to make a module out of it without writing to disk.</p>

<p>When I try using imp and a StringIO object to do this, I get:</p>

<pre><code>&gt;&gt;&gt; imp.load_source('my_module', '', StringIO('print "hello world"'))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: load_source() argument 3 must be file, not instance
&gt;&gt;&gt; imp.load_module('my_module', StringIO('print "hello world"'), '', ('', '', 0))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: load_module arg#2 should be a file or None
</code></pre>

<p>How can I create the module without having an actual file?  Alternatively, how can I wrap a StringIO in a file without writing to disk?</p>

<p><strong>UPDATE:</strong></p>

<p>NOTE: This issue is also a problem in python3.</p>

<p>The code I'm trying to load is only partially trusted.  I've gone through it with ast and determined that it doesn't import anything or do anything I don't like, but I don't trust it enough to run it when I have local variables running around that could get modified, and I don't trust my own code to stay out of the way of the code I'm trying to import.</p>

<p>I created an empty module that only contains the following:</p>

<pre><code>def load(code):
    # Delete all local variables
    globals()['code'] = code
    del locals()['code']

    # Run the code
    exec(globals()['code'])

    # Delete any global variables we've added
    del globals()['load']
    del globals()['code']

    # Copy k so we can use it
    if 'k' in locals():
        globals()['k'] = locals()['k']
        del locals()['k']

    # Copy the rest of the variables
    for k in locals().keys():
        globals()[k] = locals()[k]
</code></pre>

<p>Then you can import <code>mymodule</code> and call <code>mymodule.load(code)</code>.  This works for me because I've ensured that the code I'm loading does not use <code>globals</code>.  Also, the <code>global</code> keyword is only a parser directive and can't refer to anything outside of the exec.</p>

<p>This really is way too much work to import the module without writing to disk, but if you ever want to do this, I believe it's the best way.</p>
