Nested Scopes in Idle/PythonWin

Michael Hudson mwh21 at cam.ac.uk
Sun Apr 22 18:39:11 EDT 2001


"Tim Peters" <tim.one at home.com> writes:

> [Greg Chapman]
> > No, I'm talking about the interactive interpreter:
> >
> > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> > Type "copyright", "credits" or "license" for more information.
> > IDLE 0.8 -- press F1 for help
> > >>> def make_adder(x):
> >         return lambda y: x+y
> > SyntaxError: local name 'x' in 'make_adder' shadows use of 'x' as
> >    global in nested scope 'lambda' (<pyshell#1>, line 1)
> 
> [Jeremy Hylton]
> > You didn't tell the interpreter that you wanted to use nested scopes.
> >
> > >>> from __future__ import nested_scopes
> > >>> def make_adder(x):
> > ...	return lambda y: x + y
> > ...
> > >>>
> 
> Greg is using IDLE, not a cmdline Python, and it doesn't work in IDLE.  This
> has been listed as an unresolved issue in PEP 236 all along:
> 
> Unresolved Problem: Simulated Interactive Shells
> 
>     Interactive shells "built by hand" (by tools such as IDLE and
>     Emacs Python-mode) should behave like native interactive shells
>     (see above).  However, the machinery used internally by native
>     interactive shells has not been exposed, and there isn't a clear
>     way for tools building their own interactive shells to achieve
>     the desired behavior.
> 
> That's still the case (else I would have updated the PEP to say something
> else there <wink>).

Came up with this (after much swearing, it has to be said):

def default_compile(string,fname,mode):
    return compile(string,fname,mode)

_code = common.copy_code_with_changes(
    default_compile.func_code,flags = default_compile.func_code.co_flags|16)

nested_compile = new.function(_code, globals(), "nested_compile")

common.copy_code_with_changes is from bytecodehacks, and is just a
convenience function.

Fourth (optional) argument to __builtin__.compile, anyone?  I'd submit
a patch to code{,op}.py but if nested scopes are going to be the
default in 2.2 there ain't a lot of point.

Bah.  This is annoyingly crap, I'm afraid.  I wish I'd known about
this before 2.1 went out.

Cheers,
M.

-- 
112. Computer Science is embarrassed by the computer.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html



More information about the Python-list mailing list