Basic question about speed/coding style/memory

Thomas 'PointedEars' Lahn PointedEars at web.de
Sat Jul 21 21:19:42 CEST 2012


Jan Riechers wrote:

> I have one very basic question about speed,memory friendly coding, and
> coding style of the following easy "if"-statement in Python 2.7, but Im
> sure its also the same in Python 3.x
> 
> Block
> #----------------------------------
> if statemente_true:
> doSomething()
> else:
> doSomethingElseInstead()
> 
> #----------------------------------
> 
> versus this block:
> #----------------------------------
> if statement_true:
> doSomething()
> return
> 
> doSomethingElseInstead()
> 
> #----------------------------------
> 
> 
> I understand the first pattern that I tell the interpreter to do:

A common misconception.  As a writer of Python source code, (usually) you 
never tell the (CPython) interpreter anything (but to start working on the 
source code).  Python source code is automatically *compiled* into bytecode 
by the (CPython) interpreter, and that bytecode is executed by a virtual 
machine.¹  So at most, you are telling that virtual machine to do something, 
through the bytecode created from your source code.

> Check if the conditional is true, run "doSomething()" else go inside the
> else block and "doSomethingElseInstead()".
> 
> while the 2nd does only checks:
> doSomething() if statement_true, if not, just go directly to
> "doSomethingElseInstead()
> 
> 
> Now, very briefly, what is the better way to proceed in terms of
> execution speed, readability, coding style?

Since this is comp.lang.python, you just need to check against the Zen of 
Python to know what you should do ;-)

<http://www.python.org/dev/peps/pep-0020/>

For me, this boils down in this case to the common recommendation "return 
early, return often" as "explicit is better than implicit" and "readability 
counts".  If there is nothing else than the `else' block in the function, 
there is no use for you to continue in the function, so you should return 
explicitly at this point.

On the other hand, if you can *avoid repeating code* in each branch by _not_ 
returning in the first branch, you should do that instead ("practicality 
beats purity").

HTH

_____
¹  This is not unlike in other so-called "scripting languages"; although for
   reasons that escape me, the software that compiles the source code – the
   compiler – is called the (C)Python *interpreter*, even in
   <http://docs.python.org/faq/general.html>.
-- 
PointedEars

Please do not Cc: me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list