for -- else: what was the motivation?

Chris Angelico rosuav at gmail.com
Mon Oct 10 06:36:15 EDT 2022


On Mon, 10 Oct 2022 at 20:46, Karsten Hilbert <Karsten.Hilbert at gmx.net> wrote:
>
> Am Sun, Oct 09, 2022 at 09:58:14AM +0000 schrieb Stefan Ram:
>
> >   I often follow this rule. For me, it's about readability. Compare:
> >
> > if not open( disk ):
> >     error( "Can't open disk" )
> > else:
> >     printf( "now imagine there's some larger block here" )
>                 ... ad infinitum ....
>
> Should this not be
>
>         if not open( disk ):
>             error( "Can't open disk" )
>         else:
>                 do_lots_of_things_with(disk)
>
> as for readability ?
>
> Or even
>
>         if not open( disk ):
>             error( "Can't open disk" )
>             return what_needs_to_be_returned
>
>         do_lots_of_things_with(disk)
>
> The latter version may need some code reorganization, though.

 I definitely prefer the fail-and-bail version (mainly because, as the
number of possible failure modes increases, the code complexity
increases linearly, whereas with if/else style it will increase
quadratically - you have to edit the entire block, and indent it, for
each one). But contrasting the original two? A complete wash. There's
no readability difference between them.

ChrisA


More information about the Python-list mailing list