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

Chris Angelico rosuav at gmail.com
Thu Apr 12 02:49:42 EDT 2018


On Thu, Apr 12, 2018 at 4:45 PM, Michel Desmoulin
<desmoulinmichel at gmail.com> wrote:
>
>
> Le 11/04/2018 à 23:34, George Leslie-Waksman a écrit :
>> I really like this proposal in the context of `while` loops but I'm
>> lukewarm in other contexts.
>>
>> I specifically like what this would do for repeated calls.
>>
>> ...
>>
>> md5 = hashlib.md5()
>> with open(filename, 'rb') as file_reader:
>>     while chunk := file_reader.read(1024):
>>         md5.update(chunk)
>>
>> seems really nice. I'm not sure the other complexity is justified by
>> this nicety and I'm really wary of anything that makes comprehensions
>> more complicated; I already see enough comprehension abuse to the point
>> of illegibility.
>>
>> --George
>>
>>
>
> I like the new syntax, but you can already do what you want with iter():
>
>
> md5 = hashlib.md5()
> with open('/etc/fstab', 'rb') as file_reader:
>     for chunk in iter(lambda: file_reader.read(1024), b''):
>         md5.update(chunk)
>
> Anyway, both use case fall short IRL, because you would wrap read in
> huge try/except to deal with the mess that is letting a user access the
> filesystem.

That works ONLY if you're trying to check for a sentinel condition via
equality. So that'll work for the file read situation, but it won't
work if you're watching for any negative number (from APIs that use
negative values to signal failure), nor something where you want the
condition to be "is not None", etc, etc, etc. Also, it doesn't read
nearly as well.

ChrisA


More information about the Python-ideas mailing list