Re: [Python-Dev] PEP 572 and assert

2018年7月17日 12:21:31 -0700

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
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to