
2023-08-01 18:14 UTC+02:00, Chris Angelico <rosuav@gmail.com>:
On Wed, 2 Aug 2023 at 02:02, Celelibi <celelibi@gmail.com> wrote:
If later on an "except" is added, the developper doing the modification should be reminded to move the call to no_error_occurred() into an "else". With real-world non-trivial code, it might not be so simple to see.
Can you give us an example of real-world non-trivial code that would benefit from this?
I guess Daniel Walker (OP) would be the best to answer that since he's the one who came up with this need. I've rarely used 'else' with a 'try'. Actually, now that I think about it, I guess a 'try' block without an 'except' and just a 'finally' would probably be a good candidate for a context manager. (Which I'm a big fan of. ^^) Here's what I think could be a not so far fetched example: writing a structured file through a serializing class. Conceptually the code could look like this: myfile = MySerializer("foo.bin") try: # Write data with myfile.write() else: # Write footer with myfile.write() finally: myfile.close() You might want to keep it as a 'try' statement instead of a 'with' because in the future you might want to handle some the exceptions generated by MySerializer but not those generated by the OS. (Although I agree, you can have a 'try' in a 'with'.) And in the real world, that code might look something like this. It write two blocks of data, each preceeded by the data length and followed by a checksum. And the footer is the checksum of the whole data. assert len(data) <= 256 myfile = MySerializer("foo.bin") try: myfile.write(128) myfile.write(data[:128]) myfile.write(crc32(data[:128])) myfile.write(len(data) - 128) myfile.write(data[128:]) myfile.write(crc32(data[128:])) myfile.write(crc32(data)) finally: myfile.close() I don't know about you, but I don't think it's obvious which 'write' should be put in an 'else' block when an 'except' gets added. Even if we added comments to identify the data blocks and footers, it's not obvious that the exceptions that could be raised by writing the footer shouldn't be captured by the future 'except'. This example is not perfect, but here it is. Celelibi