Python style guidelines

Rocco Moretti roccomoretti at hotpop.com
Wed Mar 17 14:22:30 EST 2004


Heather Coppersmith wrote:

> On 12 Mar 2004 23:08:19 -0800,
> jcb at iteris.com (MetalOne) wrote:

>>Some guidelines recommend functions with only a single return
>>point.  I don't understand why this insanity got started.  At
>>one point it was recognized that multiple entry points into a
>>function was confusing, but why did it have to get extrapolated
>>to multiple exit points.  Upon entry to a function, I sometimes
>>like to verify that everything is ok before proceeding and if it
>>is not just get out.  Parameters can validated, resources
>>acquired, or whatever.
> 
> 
> It's that "resources acquired" part that messes people up.  I've
> seen it over and over and over again.  Memory leaks.  Dangling
> pointers.  Unrecoverable file handles.  Especially as functions
> that acquire lots of resources evolve over time and someone adds
> code to acquire another resource or detect another error condition
> and then doesn't find all the subsequent exit points.  It's less
> of an issue with languages with proper garbage collection, but it
> can be a real nightmare in (e.g.) C or assembler.  Unit tests that
> cover all possible resource leaks are difficult to construct
> correctly.  C++ partially addresses the problem with RIAA (if
> coders use it properly) and a hodgepodge of "smart" objects that
> do pseudo self-garbage collection.

Unfortunately, the way I've seen "single exit points" handled in complex 
functions is either to use a flag variable, which may or may not 
correspond to the temporary variable for storing the return value, or to 
enclose the whole function in an try: except block, raising a 
specialized exception to quit. Neither of these is too elegant in my 
opinion, and runs into the same problems seen with breaking out of 
deeply nested loops. (A suggestion for which on a recent thread, BTW, 
was to put them in a function and use return from multiple points).

Perhaps someone should write up a PEP:

def fun(params):
	#Function body
finally:
	#Cleanup code

Disavowing-all-responsibility-(Unless-Guido-likes-it)-ly'rs

-Rocco



More information about the Python-list mailing list