import from a string

iu2 israelu at elbit.co.il
Thu Nov 5 00:53:17 EST 2009


On Nov 4, 8:51 pm, Terry Reedy <tjre... at udel.edu> wrote:
> Gabriel Genellina wrote:
> > En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <isra... 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- Hide quoted text -
>
> - Show quoted text -

n2 :-)



More information about the Python-list mailing list