IDLE being too clever checking nonlocal declarations?

Terry Reedy tjreedy at udel.edu
Mon Oct 21 23:26:28 EDT 2013


On 10/21/2013 7:52 PM, Steven D'Aprano wrote:
> On Mon, 21 Oct 2013 15:51:56 -0400, Terry Reedy wrote:
>
>> On 10/21/2013 11:06 AM, Chris Angelico wrote:
>>> Try typing this into IDLE:
>>>
>>>>>> def a():
>>>       def b():
>>>           nonlocal q
>>> SyntaxError: no binding for nonlocal 'q' found
>>
>> If you submit those three lines to Python from the command line, that is
>> what you see.
>
> Arguably, that's also too strict,

As I quoted from the doc, it is an error for a program to contain a 
nonlocal with no referent. The reason is one only needs nonlocal to bind 
and unlike with 'global newname', it would be undefined where to do the 
binding.

def a():
   def b():
     def c():
       nonlocal q; q = 1

Where does q go? Replace nonlocal with global and there is no issue.

 > but these *four* lines work fine interactively:
>
> py> def a():
> ...     def b():
> ...             nonlocal q
> ...     q = 1

Chris had something like this.

> and also from the command line:
>
>
> [steve at ando ~]$ python3.3 -c "def a():
>>      def b():
>>          nonlocal q
>>      q = 1
>> "

What system lets you do that? (See other thread about Windows not 
allowing that, because newline terminates the command even after ".) Is 
'>' a line continuation marker (like '...' in Python)?

> so it should also work in IDLE.

I agree, and implied such on the tracker issue
http://bugs.python.org/issue19335

The question is "what does Idle do differently from the C level 
interpreter". The answer is that is subclasses the Python-coded 
code.InteractiveInterpreter. Call this II. II.runsource compiles 
*cumulative* source ultimately with the Python-coded 
codeop._maybe_compile, which returns a code object (source complete and 
valid) or None (source incomplete) or raises (source complete but not 
valid). The bug is seeing the three line input as 'complete but invalid' 
rather than as 'incomplete' (as the regular interpreter must).

To verify that this is not an Idle bug:
C:\Programs\Python33>python -m code
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
 >>> def a():
...  def b():
...   nonlocal c
   File "<string>", line None
SyntaxError: no binding for nonlocal 'c' found

There is a bit more on the tracker.

-- 
Terry Jan Reedy




More information about the Python-list mailing list