[Python-ideas] Inline assignments using "given" clauses

Cameron Simpson cs at cskk.id.au
Sun May 13 17:00:27 EDT 2018

On 13May2018 06:45, Eric V. Smith <eric at trueblade.com> wrote:
>On 5/13/18 1:05 AM, Chris Angelico wrote:
>>On Sun, May 13, 2018 at 2:58 PM, Cameron Simpson <cs at cskk.id.au> wrote:
>>>On 13May2018 14:23, Chris Angelico <rosuav at gmail.com> wrote:
>>>[...] I'd already looked at that part of the PEP and found
>>>its explaination... unfulfilling. It says:
>>> EXPR as NAME:
>>>   stuff = [[f(x) as y, x/y] for x in range(5)]
>>> Since EXPR as NAME already has meaning in except and with statements (with
>>> different semantics), this would create unnecessary confusion or require
>>> special-casing (eg to forbid assignment within the headers of these
>>> statements).
>>There were a large number of posts, so I can't really point to one of
>>them. The problem isn't the double-as case that you describe; it's
>>that these two are ALMOST identical:
>>with expr as target:
>>with (expr as target):
>>In fact, they are functionally identical for many situations - "with
>>(open(...) as target):" is exactly the same as the form without the
>>parens. It'd make for data-dependent bugs, which are a really REALLY
>>bad idea.
>A little more detail:
>The first one is partially:
>target = expr.__enter__()
>The second one is partially:
>target = expr
>For many objects, obj.__enter__() just returns obj, it often looks 
>like these two statements do the same thing, but they do not.

Ah, thank you!

Technically I knew this; in practice I'd forgotten and was thus vulnerable in 
exactly the same way as you anticipate.

>Chris's concern, which I share, is that users wouldn't know why these are 
>different, and why the second on works for some objects but not others.

While I can see the issue, on a personal basis I'd accept it: import and except 
don't do this and they happily use "as". In my mind the problem lies with 
"with" (and is a perfectly acceptable inconsistency there, given what with does 
for us).  I agree the change in semantics is not obvious. But we've got a 
similar thing with tuples as well:

  x = (1)
  x = (1,)

with a different spelling.

>I agree the PEP could use more detail in explaining this particular issue.

Yes. This issue certainly isn't clear to me from the PEP's wording.

I'm no longer trying to push the "as" agenda here, BTW. I still like it, but 
that ship seems sailed.

Cameron Simpson <cs at cskk.id.au>

More information about the Python-ideas mailing list