[Python-ideas] PEP 572: Assignment Expressions (post #4)

Chris Angelico rosuav at gmail.com
Wed Apr 11 17:28:28 EDT 2018


On Thu, Apr 12, 2018 at 1:22 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>>     # Similar to the boolean 'or' but checking for None specifically
>>     x = "default" if (eggs := spam().ham) is None else eggs
>>
>>     # Even complex expressions can be built up piece by piece
>>     y = ((eggs := spam()), (cheese := eggs.method()), cheese[eggs])
>>
>
> Leading with these kinds of examples really doesn't help to sell the
> proposal, since they're hard to read, and don't offer much, if any,
> benefit over the status quo where assignments (and hence the order of
> operations) need to be spelled out as separate lines.
>
> Instead, I'd suggestion going with the kinds of examples that folks
> tend to bring up when requesting this capability:

Cool, thanks. I've snagged these (and your other examples) and
basically tossed them into the PEP unchanged.

>> The name ``prefix`` is thus searched for at global scope, ignoring the class
>> name. Under the proposed semantics, this name will be eagerly bound, being
>> approximately equivalent to::
>>
>>     class X:
>>         names = ["Fred", "Barney", "Joe"]
>>         prefix = "> "
>>         def <listcomp>(prefix=prefix):
>>             result = []
>>             for name in names:
>>                 result.append(prefix + name)
>>             return result
>>         prefixed_names = <listcomp>()
>
> "names" would also be eagerly bound here.

Yep, that was a clerical error on my part, now corrected.

>> Frequently Raised Objections
>> ============================
>
> There needs to be a subsection here regarding the need to call `del`
> at class and module scope, just as there is for loop iteration
> variables at those scopes.

Hmm, I'm not sure I follow. Are you saying that this is an objection
to assignment expressions, or an objection to them not being
statement-local? If the latter, it's really more about "rejected
alternative proposals".

>> This could be used to create ugly code!
>> ---------------------------------------
>>
>> So can anything else.  This is a tool, and it is up to the programmer to use it
>> where it makes sense, and not use it where superior constructs can be used.
>
> This argument will be strengthened by making the examples used in the
> PEP itself more attractive, as well as proposing suitable additions to
> PEP 8, such as:
>
> 1. If either assignment statements or assignment expressions can be
> used, prefer statements
> 2. If using assignment expressions would lead to ambiguity about
> execution order, restructure to use statements instead

Fair enough. Also adding that chained assignment expressions should
generally be avoided.

Thanks for the recommendations!

ChrisA


More information about the Python-ideas mailing list