[Python-ideas] Inline assignments using "given" clauses
ncoghlan at gmail.com
Fri May 11 07:43:01 EDT 2018
On 11 May 2018 at 03:33, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Gustavo Carneiro wrote:
>> IMHO, all these toy examples don't translate well to the real world
>> because they tend to use very short variable names while in real world
>> [good written code] tends to select longer more descriptive variable names.
> I don't believe that's always true. It depends on the context.
> Sometimes, using long variable names can make code *harder*
> to read.
> I don't think there's anything unrealistic about this
> if m given m = pattern.match(the_string):
> nugget = m.group(2)
> Most people's short-term memory is good enough to remember
> that "m" refers to the match object while they read the
> next couple of lines. IMO, using a longer name would serve
> no purpose and would just clutter things up.
I've been thinking about this problem, and I think for the If/elif/while
cases it's actually possible to allow the "binding is the same as the
condition" case to be simplified to:
if command = pattern.match(the_string):
elif command = other_pattern.match(the_string):
while data = read_data():
Allowing this would be part of the definition of the if/elif/while
statement headers, rather than a general purpose assignment expression.
The restriction of the LHS to a simple name target would need to be in the
AST generator rather than in the grammar, but it's hardly the only case
where we do that kind of thing. Switching to the given expression form
would then only be necessary in cases where the condition *wasn't* the same
as the binding target.
A similar enhancement could be made to conditional expressions (adjusting
their grammar to permit "EXPR if NAME = EXPR else EXPR") and filter clauses
in comprehensions (allowing "EXPR for TARGET in EXPR if NAME = EXPR"). In
essence, "if", "elif", and "while" would all allow for an "implied given"
clause in order to simplify the 90% case where the desired condition and
the bound expression are the same.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas