import from a string

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Nov 3 20:10:51 EST 2009


En Tue, 03 Nov 2009 17:36:08 -0300, iu2 <israelu at elbit.co.il> escribió:
> On Nov 3, 7:49 pm, Matt McCredie <mccre... at gmail.com> wrote:
>> iu2 <israelu <at> elbit.co.il> writes:
>>
>> > Having a file called funcs.py, I would like to read it into a string,
>> > and then import from that string.
>> > That is instead of importing from the fie system, I wonder if it's
>> > possible to eval the text in the string and treat it as a module.

>> mymodule = types.ModuleType("mymodule", "Optional Doc-String")
>> with file('funcs.py') as f:
>>     txt = f.read()
>> exec txt in globals(), mymodule.__dict__
>> sys.modules['mymodule'] = mymodule
>
> Thanks, it seems simpler than I thought.
> I don't fully understand , though, the exec statement, how it causes
> the string execute in the context of mymodule.

Sometimes you don't even require a module, and this is simpler to  
understand. Suppose you have a string like this:

txt = """
def foo(x):
   print 'x=', x

def bar(x):
   return x + x
"""

you may execute it:

py> namespace = {}
py> exec txt in namespace

The resulting namespace contains the foo and bar functions, and you may  
call them:

py> namespace.keys()
['__builtins__', 'foo', 'bar']
py> namespace['foo']('hello')
x= hello

exec just executes the string using the given globals dictionary as its  
global namespace. Whatever is present in the dictionary is visible in the  
executed code as global variables (none in this example). The global names  
that the code creates become entries in the dictionary. (foo and bar;  
__builtins__ is an implementation detail of CPython). You may supply  
separate globals and locals dictionaries.

-- 
Gabriel Genellina




More information about the Python-list mailing list