[Python-Dev] PEP 572: Now with 25% less reference implementation!

Chris Angelico rosuav at gmail.com
Fri Apr 20 02:31:32 EDT 2018


On Fri, Apr 20, 2018 at 2:45 PM, Dmitry Malinovsky <damalinov at gmail.com> wrote:
> Hello Chris, and thank you for working on this PEP!
>
> What do you think about using variable type hints with this syntax?
> I tried to search through python-dev and couldn't find a single post
> discussing that question.
> If I missed it somehow, could you please include its conclusions into the PEP?

I'm ignoring them for the sake of the PEP, because it'd complicate the
grammar for little benefit. If someone wants to add an enhancement
later, that's fine; but the proposal can stand without it, and with
it, it'll make for even more noise in a line full of colons.

> For instance, as I understand now the parser will fail on this snippet:
>
>     while data: bytes := stream.read():
>         print("Received data:", data)
>
> Do brackets help?
>
>     while (data: bytes := stream.read()):
>         print("Received data:", data)
>
> IIUC, in 3.7 It is invalid syntax to specify a type hint for a for loop item;
> should brackets help? Currently they don't:
>
>     Python 3.7.0b3+ (heads/3.7:7dcfd6c, Mar 30 2018, 21:30:34)
>     [Clang 9.0.0 (clang-900.0.39.2)] on darwin
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> for (x: int) in [1,2,3]:
>       File "<stdin>", line 1
>         for (x: int) in [1,2,3]:
>           ^
>     SyntaxError: invalid syntax

And that's another good reason not to bother, at least for now. I'm
not sure whether you can use a Py2-style type hint comment on a for
loop, but if so, you should also be able to do it on a while loop or
anything. Or, of course, you can just annotate the variable before the
loop, if you want to.

ChrisA


More information about the Python-Dev mailing list