There is also the, I think seldom used, feature that calling python with '-O' removes all assert statements at parse/compile time (I believe for performance reasons)
So for example: $ python -c 'assert False' Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError But: $ python -O -c 'assert False' [no output] $ Ignoring the question about this feature being particularly useful, it would be much harder to implement if assert were a standard function (and re-bindable), as the 'arguments' in the assert construct are not even executed when '-O' is used (this is the performance gain): $ python -O -c 'assert DoesNotExist' Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'DoesNotExist' is not defined vs. $ python -O -c 'assert DoesNotExist' [no output] $ so the compiler would have to do a lot of work to identify assert calls and remove them. Steve On Tue, Mar 2, 2021 at 9:04 PM Chris Angelico <ros...@gmail.com> wrote: > On Wed, Mar 3, 2021 at 7:53 AM Marco Sulla <marco.sulla.pyt...@gmail.com> > wrote: > > > > I have a curiosity. Python, as many languages, has assert as a > > keyword. Can't it be implemented as a function? Is there an advantage > > to have it as a keyword? > > It could, but it would need some magic. A lot of test frameworks have > their own set of assertions and you have to pick the one you want - > for instance: > > assertEqual(x, y) > > instead of > > assert x == y > > The trouble is that, if you write a function for this, it will just > get True or False, without any explanation of the cause - making it > somewhat unhelpful when something goes wrong. To compensate, function > equivalents inevitably have to have myriad types of assertions, where > the language just needs one. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list