On Sat, Mar 13, 2021 at 12:11 AM Richard Damon <rich...@damon-family.org> wrote: > > On 3/12/21 12:31 AM, Chris Angelico wrote: > > On Fri, Mar 12, 2021 at 3:53 PM Cameron Simpson <c...@cskk.id.au> wrote: > >> 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. > > Something like that, yeah. An assertion failure represents a bug *in > > this code*, something that shouldn't ever happen. If it's possible to > > trigger the failure with some other piece of code (calling something > > with bad arguments, or whatever), then assert is the wrong tool for > > the job. Similarly, if you find yourself catching AssertionError > > anywhere outside of unit testing, something is horribly wrong > > somewhere :) > > > > ChrisA > > Chris, I would disagree with that statement. An assert says that there > is something wrong with THE code, not THIS code. It is perfectly > reasonable, and good defensive programming, to assert on the > per-conditions to the procedure at its beginning. > > Now, it may be true that a 'friendlier' procedure may be defined to > check some of these and return an error, but that then locks that > behavior into the API, so the cost of the check becomes an absolute > requirement. >
It's perfectly reasonable to put "if condition: raise Blah", but is it really reasonable to use the assert statement, which (a) might not be run, and (b) raises a very generic exception? Make assertions about your own code, not other people's. ChrisA -- https://mail.python.org/mailman/listinfo/python-list