04.05.18 15:06, Nick Coghlan пише:
Recapping the use cases where the inline assignment capability received the most agreement regarding being potentially more readable than the status quo:

Sorry, but these examples don't look as good examples for inline assignments to me. I think that all these cases can be written better without using the inline assignment.

1. Making an "exactly one branch is executed" construct clearer than is the case for nested if statements:

     if m := pattern.search(data):
         ...
     elif m := other_pattern.search(data):
         ...
     else:
         ...

This case can be better handled by combining patterns in a single regular expression.

    pattern = re.compile('(?P<foo>pattern1)|(?P<bar>pattern2)|...')
    m = pattern.search(data)
    if not m: # this can be omitted if the pattern is always found
        ...
    elif m.group('foo'):
        ...
    elif m.group('bar'):
        ...

See for example gettext.py where this pattern is used.

2. Replacing a loop-and-a-half construct:

     while m := pattern.search(remaining_data):
         ...

This case can be better handled by re.finditer().


    for m in pattern.finditer(remaining_data):
        ...

In more complex cases it is handy to write a simple generator function and iterate its result.

The large number of similar cases are covered by a two-argument iter().

3. Sharing values between filtering clauses and result expressions in comprehensions:

     result = [(x, y, x/y) for x in data if (y := f(x))]

There are a lot of ways of writing this. PEP 572 mentions them. Different ways are used in real code depending on preferences of the author. Actually the number of these cases is pretty low in comparison with the total number of comprehensions.

It is possible to express an assignment in comprehensions with the "for var in [value]" idiom, and this idiom is more powerful than PEP 572 in this case because it allows to perform an assignment before the first 'for'. But really complex comprehensions could be better written as 'for' statements with explicit adding to the collection or yielding.

_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to