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

Eric V. Smith eric at trueblade.com
Sun May 13 06:45:29 EDT 2018


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:
>>>
>>> On Sun, May 13, 2018 at 2:05 PM, Cameron Simpson <cs at cskk.id.au> wrote:
>>>>
>>>> Could someone point me to a post which nicely describes the rationale
>>>> behind
>>>> its rejection?  I'm sure there's one in the many in this discussion but
>>>> I've
>>>> not found it yet.
>>>
>>>
>>>
>>> https://www.python.org/dev/peps/pep-0572/#special-casing-conditional-statements
>>> https://www.python.org/dev/peps/pep-0572/#alternative-spellings
>>>
>>> I'm not sure which version you're looking at, so there's the rejections of
>>> both.
>>
>>
>> I meant the latter, but 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).
>>
>> All you need to disambiguate, say:
>>
>>  with expr as expr_as as with_as:
>>
>> is to require parentheses for (expr as exp_as) if someone wanted that
>> complications (assuming that is even necessary - it seems unambiguous to my
>> eye already, unless the token lookahead requirement in Python's grammar
>> prevents that.
>>
>> So I'd hoped for a post to the list discussing this aspect and outlining why
>> it was considered unsatisfactory.
>
> 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. 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.

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

Eric


More information about the Python-ideas mailing list