Why assert is not a function?

Chris Angelico rosuav at gmail.com
Tue Mar 2 16:01:50 EST 2021


On Wed, Mar 3, 2021 at 7:53 AM Marco Sulla <Marco.Sulla.Python at 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


More information about the Python-list mailing list