[Python-3000] Backward compatibility for "nonlocal"

Ka-Ping Yee python at zesty.ca
Mon Nov 6 00:57:14 CET 2006


As an aside to the discussion about "nonlocal", here are a couple of
thoughts on backward compatibility.

For some of the proposed keywords, here's the number of occurrences
of the keyword in the current standard library (not including comments
and docstrings):

    nonlocal      0       0
    use           2       2
    using         3       3
    reuse         0       4
    free          8       8
    outer         5     147
    global      126     214

(I used 'tokenize' to do this; let me know if you'd like me to count
other possibilities.)

This may or may not be a good measure of the likely impact of adding
a new keyword.  At least it's something to think about.

It also occurred to me that this new keyword doesn't necessarily
have to break anything, if we are willing to tolerate a little
hackery in the Python lexer and parser.  The situation is a bit
reminiscent of 'as' -- we were able to add 'as' to the 'import'
statement as though 'as' were a keyword, without actually making
'as' a reserved word in all code.

In this case, the usage of "nonlocal" (or whatever we choose) as
a keyword never overlaps with its usage as a variable name.  The
parser could easily tell the difference by checking whether:

    - The keyword is at the beginning of a statement.
    - The keyword is immediately followed by an identifier.

If both of these things are true, then the keyword is a nonlocal
declaration.  Otherwise, it can be treated as a variable name.

I'm not saying this is necessarily a good idea; i just wanted to
note that it was an available option.  We might think about a
schedule for phasing in the feature:

    Phase 1.  If "nonlocal" is seen in code, issue a warning
              that it will become a keyword in a future version.

    Phase 2.  Have the parser distinguish when "nonlocal" is
              intended as a keyword and when as a variable name.

    Phase 3.  Make "nonlocal" an official reserved word.

All of these phases are optional -- we could skip straight to 3,
or do 1 and then 3, or stop at 2, etc.


-- ?!ng


More information about the Python-3000 mailing list