On 14/05/2022 04.37, bryangan41 wrote: > Is the following LBYL:foo = 123if foo < 200: do()
Yes (once formatted for Python). If so, how to change to EAFP? Not sure if can. Let's alter the code to: foo = 0 #and def do(): return 5 / foo Then, you will expect a ZeroDivisionError exception to be raised - whereas with other values, there will (likely) be no problem. Now, we have a clear identification for when 'forgiveness' will need to be requested! The 'EAFP' solution encloses the function-call: foo = 123 try: do() except ZeroDivisionError: undo() In the OP's code-snippet, the "200" criteria means there is no such clean-cut and automatic 'failure' attached to, or implied by, foo's value. However, we could define a custom-exception and 'raise the alarm' when 'forgiveness' is required: class ValueTooLargeError( ValueError): """Catch values larger than the valid range.""" def do(): if foo < 200: ... else: raise ValueTooLargeError This is a pythonic-construct (and thus a recommendable coding-pattern), in that the calling-routine can decide how to respond to the exception - which many vary according to the specifics of do()'s re-use. However, is it "EAFP"? We had to introduce the exact if-condition which makes it "LBYL"! Perhaps time for me to bow-out, and leave such to the philosophers... Sent from Samsung tablet. There are pills for that... -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list