Basic question about speed/coding style/memory

Chris Angelico rosuav at
Sat Jul 21 11:04:12 CEST 2012

On Sat, Jul 21, 2012 at 5:33 PM, Jan Riechers <janpeterr at> wrote:
> Block
> #----------------------------------
> if statemente_true:
>         doSomething()
> else:
>         doSomethingElseInstead()
> #----------------------------------

This means, to me, that the two options are peers - you do this or you do that.

> versus this block:
> #----------------------------------
> if statement_true:
>         doSomething()
>         return
> doSomethingElseInstead()
> #----------------------------------

This would be for an early abort. Don't bother doing most of this
function's work, just doSomething. Might be an error condition, or
perhaps an optimized path.

Definitely for error conditions, I would use the second option. The
"fail and bail" notation keeps the entire error handling in one place:

def func(x,y,z):
  if x<0:
  if y<0:
    raise PEBKAC("There's an idiot here somewhere")
  # ... do the rest of the work

Note the similarity between the control structures. Raising an
exception immediately terminates processing, without polluting the
rest of the function with an unnecessary indentation level. Early
aborting through normal function return can do the same thing.

But this is purely a matter of style. I don't think there's any
significance in terms of processing time or memory usage, and even if
there is, it would be dwarfed by considerations of readability. Make
your code look like what it's doing, and let the execution take care
of itself.


More information about the Python-list mailing list