On Tue, Feb 11, 2020 at 07:10:18PM -0000, jdve...@gmail.com wrote: > I have been taught that assertions must not produce side effects at all.
That's good practice, but saying that they "must not" is too strong. The risk here is not the side-effect, but relying on that side-effect (which may be disabled) outside of the assertion. Some side-effects are perfectly fine: assert log(message) or condition > This is a problem in languages such as C. But not in Python (until > 3.8) since it does not allow assignment expressions. Assignment is not the only possible side-effect. These have been possible back to Python 2.4 and probably older: assert mylist.pop() assert globals().update({'flag': expression}) or flag assert delattr(mymodule, 'spam') or condition In Python 3, we can also do things like this: assert print(message) or condition assert exec("value = expression") or condition Since assertions can call functions (and methods), and functions can have side-effects, Python has *always* been able to have side-effects inside assertions. > But now, for best or worst, we have the walrus operator Oh, definitely for the best. This now allows us to write complex assertions much more easily and efficiently: assert log(flag := complex_expression) or flag Previously we would have to write this: if __debug__: flag = complex_expression assert flag which is much less convenient, but is another way to get side-effects in an assertion. > However, if assertions are disabled: > > `python3.8 -Oc "assert (always := True); print(f'{always=}')"` > > it raises an exception: Indeed. So does this: [steve@ando ~]$ python -c "if False: always = 999 print(always)" Traceback (most recent call last): File "<string>", line 3, in <module> NameError: name 'always' is not defined and for roughly the same reason. [...] > Do not you think that disabling walrus operators in assertions would > be a good idea? No. -- Steven _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/H4YLYLRWLNUG6LNOTWSH4VVRT3MLKZGZ/ Code of Conduct: http://python.org/psf/codeofconduct/