[Python-ideas] Keyword declarations

Steven D'Aprano steve at pearwood.info
Wed May 16 20:53:46 EDT 2018


On Wed, May 16, 2018 at 07:24:19PM +0200, Adam Bartoš wrote:
> Hello,
> 
> I have yet another idea regarding the the clashes between new keywords and
> already used names. How about introducing two new keywords *wink* that
> would serve as lexical keyword/nonkeyword declarations, similarly to
> nonlocal and global declarations?
> 
> def f():
>     nonkeyword if
>     if = 2 # we use 'if' as an identifier
>     def g():
>         keyword if
>         if x > 0: pass # now 'if' again introduces a conditional statement

This is absolutely no help at all for the common case that we have an 
identifier that is a keyword and want to use it as a keyword in the same 
block. For example, we can currently write:

    try:
        value = data.except_
    except:
        value = data.missing()

say. We're using "except_" because the data comes from some external 
interface where it uses "except", but we can't use that because its a 
keyword.

I also challenge to think about how you will document the complicated 
rules for when you can and can't use keywords as names, especially think 
about explaining them to beginners:

    def spam(None=42):
        print(None)  # What will this print?
        x = None  # Fine, but what does it do?
        None = 999  # Is this an error or not?

Remember the KISS principle.



-- 
Steve


More information about the Python-ideas mailing list