Slight irritation with try/finally indentation

François Pinard pinard at iro.umontreal.ca
Wed Apr 24 10:14:45 EDT 2002


Hello, people.

There is something which I find slightly irritating with the try/finally
construct, and wonder if someone would not have a good advice to offer.
I guess it is very usual that one has, within a suite, something like:

    [...]
    setup()
    process()
    cleanup()
    [...]

with `cleanup' undoing the effect of `setup', more or less, really seeing
`setup()' and `cleanup()' as a kind of big parentheses around `process()'.
In a context where `process()' may raise exceptions, `cleanup()' might be
mandatory once `setup()' has completed, so one rewrites the above as:

    [...]
    setup()
    try:
        process()
    finally:
        cleanup()
    [...]

What I find irritating is that `cleanup()' is not aligned anymore with
`setup()', as it was originally, so we loose on the legibility of the
parenthetical idiom we wanted to stress.  Surely, I may _not_ write:

    [...]
    try:
        setup()
        process()
    finally:
        cleanup()
    [...]

despite it would look nicer, because if `setup()' fails, `cleanup()'
gets called when it should not have been.  Resorting to tricks like:

    [...]
    if True:
        setup()
    try:
        process()
    finally:
        cleanup()
    [...]

is the only solution I see, but this is not much appealing either, maybe
the cure is not worse than the illness.  I am not sure.  Are others on
this list bothered with this issue?  And if yes, what do you choose to do?

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list