nested scopes in IDLE? (2.1)

Tim Peters tim.one at home.com
Mon Jun 4 07:40:22 CEST 2001


Kirby, "from __future__ import nested_scopes" isn't effective at the IDLE
prompt.  This was listed as an open issue in the design PEP and still isn't
resolved.  It is effective at a native shell prompt ("DOS box" on Windows),
but that has access to internal machinery that *simulated* shells (like
IDLE's and PythonWin's etc) can't get at -- at least not yet.

The easiest way to use nested scopes in IDLE is to create a new IDLE edit
window (File -> New window (Ctrl+N)), put

from __future__ import nested_scopes

at the top of it, type your code into it, and do

    Edit -> Run script

(Ctrl+F5) from time to time.  For example, I typed this into an edit window:

from __future__ import nested_scopes

def compose(f,g):
    return lambda f,g,x: f(g(x))

saved it, hit Ctrl+F5, then here's my IDLE session:

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
>>>

>>> c = compose(lambda x: x**2, lambda x: x+1)
>>> c(12)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    c(12)
TypeError: <lambda>() takes exactly 3 arguments (1 given)
>>>

That error msg is correct!  The lambda you're returning does indeed require
3 arguments, so your code will never work the way you hope.

At this point you're *glad* you had to use a separate window, because now
you can just go back and edit it (I'm just removing the unwanted arguments
to lambda here):

from __future__ import nested_scopes

def compose(f,g):
    return lambda x: f(g(x))

Save and hit Ctrl+F5 again, and here's what happens now:

>>> c = compose(lambda x: x**2, lambda x: x+1)
>>> c(12)
169
>>> c(11)
144
>>> c(0)
1
>>> c(1)
4
>>>

All is cool.





More information about the Python-list mailing list