On Tue, Jan 2, 2018 at 9:11 AM, <breamore...@gmail.com> wrote: > On Monday, January 1, 2018 at 9:35:06 PM UTC, Chris Angelico wrote: >> On Tue, Jan 2, 2018 at 7:16 AM, Chris Green wrote: >> > Dennis Lee Bieber wrote: >> >> >> >> Well... "break" does bypass the rest of the block, but it still >> >> exits >> >> via the end of the block. I have a tendency to try for one "return" per >> >> procedure (so I'm more likely to have an "if ...: break" then "if ...: >> >> return"). >> > >> > I have always tried to enforce 'only one return per function'. If >> > there are multiple returns it makes maintenance very difficult as >> > 'clear up' code can get bypassed. >> > >> >> Isn't that why try/finally exists? No matter how many 'return' >> statements you have, there's always exceptions to bypass any naive >> cleanup code; and no matter how many returns you have, 'finally' >> blocks still execute before return. >> >> ChrisA > > What happened to context managers? >
They're a way of wrapping up repeatedly-used try/finally blocks. The try/finally construct is the underlying functionality. In any case, the same behaviour can be used by either, so yes, if you have cleanup code and you're using 'with x:' rather than try/finally, it still fits into the same concept that I'm describing, and still guarantees that the cleanup code is executed before return. (Yes, I know it's possible to bypass finally blocks. But the methods for doing so (eg hard-aborting) also bypass the actual return, so the "before return" part is still valid. If you're doing things that depend on cleanup outside the process, like deleting temporary files, you'll need something more than try/finally. But in that case, there's no other code layout that would help you anyway.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list