Python 3.X: nonlocal support in eval/exec?

P

Paddy

We can access nonlocal variables in a function, but if we were to eval/
exec the function we cannot set up a nested stack of evironment dicts.
We are limited to just two: global and local.

How about eval/exec take a new env argument that is a nested
dictionary whose outer level corresponds to locals, and which has a
__up__ value which is the next outer level environment dict. The
outermost level of the nested dictionary would correspond to the
global level?

I haven't given much thought to my suggested solution - I just didn't
want to leave a possible solution out. The major point is that there
seems to be no support for nonlocal in eval/exec (unless, trivially,
nonlocal==global).

- Paddy.
 
T

Terry Reedy

We can access nonlocal variables in a function, but if we were to eval/
exec the function we cannot set up a nested stack of evironment dicts.
We are limited to just two: global and local.

Right. That was and is Python's execution model.
Note that when you exec code, including a function call, the locals
passed is the local context in which the code is executed. It is not the
locals of any particular function called by the exec-ed code.

If you exec a function that is a closure, the closure or non-local
objects come with the function. A 'stack of dicts' has nothing to do
with how function and nested funcs operate.
 
P

Paddy

Right. That was and is Python's execution model.
Note that when you exec code, including a function call, the locals
passed is the local context in which the code is executed. It is not the
locals of any particular function called by the exec-ed code.

If you exec a function that is a closure, the closure or non-local
objects come with the function. A 'stack of dicts' has nothing to do
with how function and nested funcs operate.

Thanks Terry.
 

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

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,108
Latest member
AlbertEste
Top