Using the variable type annotation syntax as a placeholder in a nonlocal scope?

Kirill Balunov kirillbalunov at gmail.com
Wed Dec 20 14:43:09 EST 2017


I've asked the same question on StackOverflow, but it seems to me that it
is opinion based and will be ignored. So I ask for advice here:

Since PEP 526 -- Syntax for Variable Annotations
<https://www.python.org/dev/peps/pep-0526/>  was approved, in Python 3.6+
it is possible to provide type hint information in the form *x: int*, also
the PEP says "However, annotating a local variable will cause the
interpreter to always make it local to the scope and leaves the variable
uninitialized". Therefore in Python 3.6+ it is syntactically legal to
write:

def outer():
    x: int
    def inner():
        nonlocal x
        x = 10
    inner()
    print(x)

while the above snippet is semantically more equivalent to:

def outer():
    #x
    def inner():
        nonlocal x
        x = 10
    inner()
    print(x)

Which is obviously a *SyntaxError: no binding for nonlocal 'x' found`*,
sorry for the pun. Also there is nothing said about this style in PEP 8 and
Python 3.6 docs. So should I consider this as a bug, or an implementation
detail (side effect), or a wart, or a feature?

To clarify the purpose of the question - we can not come to a consensus and
I would like to hear your opinion and possible pitfalls, if any, if we
choose to use this form in our codebase.

With kind regards, -gdg



More information about the Python-list mailing list