On 12Mar2021 12:53, DL Neil <pythonl...@danceswithmice.info> wrote: >On 12/03/2021 11.27, Chris Angelico wrote: >> On Fri, Mar 12, 2021 at 9:10 AM Ethan Furman <et...@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. ;-) [...] >> 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. > >Perhaps I misunderstood (and haven't gone back to check - mea culpa), >but the impression-gained was that -O many not be used, even "in >production", for some reason?
News to me. Perhaps that was someone's scenario. To me, asserts have 2 primary features: (a) they're easy to write (and read) versus "if some_test: raise SomeException("blah blah...")" and (b) they are outright _absent_ from the code when run with -O. _Provided_ the code called from the assert has no side effects, dropping the asserts should always make for identical -O behaviour vs no -O. Chris' example above walks the middle ground providing something richer that a plain assert while still (almost) vanishing with -O (and no args.verify mode switch). >Perhaps because I've not come from a language where assert played any/a >major rĂ´le, but am still hoping for some discussion/understanding as to >why/when assert might be better than try...except in every/particular >situations... I find assert visually low impact. Try/except is quite wordy and brings more indentation. One has to keep in mind the use case. For me, try/except is for when something might reasonably "go wrong" in normal use, even niche normal use. Whereas assert is for things which should _never_ occur. Roughly, again for me, try/except if for catching misuse and assert is for catching misdesign/misimplementation. Cheers, Cameron Simpson <c...@cskk.id.au> -- https://mail.python.org/mailman/listinfo/python-list