[Python-Dev] PEP 572 and assert

Tim Peters tim.peters at gmail.com
Tue Jul 17 12:25:05 EDT 2018


[Serhiy Storchaka]

> Recently Barry shown an example:
>
>      assert len(subdirs := list(path.iterdir())) == 0, subdirs
>
> It looks awful to me. It looks even worse than using asserts for
> validating the user input. The assert has a side effect, and it depends
> on the interpreter option (-O). Even if subdirs is not used outside of
> the assert *now*, it is easy to introduce an error later, and it is hard
> to notice it if tests are not ran with the -O option regularly.
>


Does PEP 572 encourages writing such code, discourages this, or
> completely forbids?
>

The body of the PEP specifies semantics.  My Appendix A gives some
_opinions_ about "good" and "bad" uses, which boil down to "if it's not
obviously at least a little win, don't use it".

I can't really guess whether the above is an obvious win or not without
context.  It is a win (to my eyes) if the code it replaced was

    if __debug__:
        subdirs = list(path.iterdir())
        assert len(subdirs) == 0, subdirs

in which case the semantics are the same in either spelling, with or
without -O, but the spelling at the top is less annoying ;-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180717/70824815/attachment.html>


More information about the Python-Dev mailing list