import from a string

Terry Reedy tjreedy at udel.edu
Wed Nov 4 13:51:02 EST 2009


Gabriel Genellina wrote:
> En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <israelu at elbit.co.il> escribió:
>> On Nov 4, 3:10 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> 
>>> txt = """
>>> def foo(x):
>>>    print 'x=', x
>>>
>>> def bar(x):
>>>    return x + x
>>> """
>>>
>>> py> namespace = {}
>>> py> exec txt in namespace
>>> py> namespace.keys()
>>> ['__builtins__', 'foo', 'bar']
>>> py> namespace['foo']('hello')
>>> x= hello
> 
>> What happens if both global and local dictionaries are supplied: where
>> are the newly created entities created? In the local dict?
> 
> The amazing thing about Python is how easy is to experiment in the 
> interpreter.
> Just see it by yourself!

Hint: they are created in the same namespace they always are (ignoring 
nested functions and nonlocal namespaces). But I agree with Gabriel: 
just try it. n1,n2={},{}; exec....

Terry Jan Reedy





More information about the Python-list mailing list