Why assert is not a function?

Chris Angelico rosuav at gmail.com
Thu Mar 11 17:27:27 EST 2021


On Fri, Mar 12, 2021 at 9:10 AM Ethan Furman <ethan at stoneleaf.us> wrote:
>
> On 3/11/21 1:45 PM, dn via Python-list wrote:
>
> > Is assert so much faster/cheaper than try...except...raise?
>
> Infinitely faster when they are not there.  ;-)
>
> Basically, you are looking at two different philosophies:
>
> - Always double check, get good error message when something fails
>
> vs
>
> - check during testing and QA, turn off double-checks for production for best performance possible.
>

There are many hybrids available too though. For instance:

if __debug__ or args.verify:
    def verify(thing):
        ...
        raise Whatever
else:
    def verify(thing): pass

Yes, you pay the price of a function call even if you're not verifying
the full structural integrity. But that's a lot cheaper than the full
check.

Advantage here is that you can use -O to suppress, or you can control
it with an arg, or whatever.

If you're doing the same check in lots of places, and it's costly,
assertions aren't really a great fit.

ChrisA


More information about the Python-list mailing list