[Python-Dev] PEP 572 and assert
python at mrabarnett.plus.com
Tue Jul 17 15:18:51 EDT 2018
On 2018-07-17 19:34, Tim Peters wrote:
> [Barry Warsaw]
> Thanks! I thought it was cute. It was just something that occurred
> to me as I was reviewing some existing code. The intent wasn’t to
> use `subdirs` outside of the assert statement, but I’m warm to it
> because it means I don’t have to do wasted work outside of the
> assert statement, or repeat myself in the assert message part.
> Because the latter ("repeat myself") is probably more tempting, I'll
> just note that the "laziness" of using an assignment expression instead
> may well have nudged you toward writing _better_ code too.
> assert len(subdirs := list(path.iterdir())) == 0, subdirs
> Assuming the result of list(path.iterdir()) can change over time (seems
> very likely),
> assert len(list(path.iterdir())) == 0, list(path.iterdir())
> _could_ end up both triggering and displaying an empty list in the
> exception detail. The assignment-expression version cannot.
Why use len(...) == 0 instead of not(...)?
assert not(subdirs := list(path.iterdir())), subdirs
More information about the Python-Dev