problem with namespaces using eval and exec

J

Jens

Hi,

has anyone an idea why the following code does not work.


s = """
def a(n):
return n*n


def b(t):
return a(t)
"""


ns = {}
exec(s, {}, ns)
eval("b(2)", ns, {})


executing this script raises an exception (NameError: global name 'a'
is not defined) in the last line.


Hope for your help.
 
M

Maric Michaud

Le Mardi 16 Mai 2006 11:05, Jens a écrit :
s = """
def a(n):
  return n*n


def b(t):
  return a(t)
"""


ns = {}
exec(s, {}, ns)
eval("b(2)", ns, {})
you passed an empty globals dictionnary to the eval func (the local one is not
in the scope of b defintion)
try this :

exec s // like exec s in globals(), locals()
eval("b(2)") // like , eval("b(2)", globals(), locals())

or if you to keep this dictionnary as a specific scope in your appplication :

exec s in ns
eval("b(2)", ns)

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
 
P

Peter Otten

Jens said:
has anyone an idea why the following code does not work.
s = """
def a(n):
return n*n
def b(t):
return a(t)
"""
ns = {}
exec(s, {}, ns)

Here you are providing a local namespace into which all toplevel names (a
and b) are inserted.
eval("b(2)", ns, {})

Here you provide a global (the former local) namespace containing an 'a'.
Function b(), however is carrying its global namespace with it and will
look for 'a' in that namespace and not the one you provide. This is similar
to

module x.py
def b(t): return a(t)

module y.py
import x
def a(t): return n * n
x.b(2) # error, will not find the function a() you just defined

Instead you could explicitly update b's global namespace:

global_ns = {}
local_ns = {}
exec s in global_ns, local_ns
global_ns["a"] = local_ns["a"]
print eval("b(2)", local_ns)

or (better, I think) model the situation of an ordinary module where
globals() and locals() are identical:

global_ns = {}
exec s in global_ns
print eval("b(2)", global_ns)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

eval and exec in an own namespace 0
use of exec() 12
Problem with exec 0
imports and exec 2
Problem with exec 2
namespaces, scoping and variables 0
Pass parameters/globals to eval 1
namespaces and eval 2

Members online

No members online now.

Forum statistics

Threads
473,787
Messages
2,569,629
Members
45,329
Latest member
InezZ76898

Latest Threads

Top