return in loop for ?

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 24 04:19:48 EST 2005


Steve Holden wrote:

>> Interestingly, I just saw a thread over at TurboGears(or is it this
>> group, I forgot) about this multiple return issue and there are people
>> who religiously believe that a function can have only one exit point.
>> 
>> def f():
>>   r = None
>>   for i in range(20):
>>   if i > 10:
>>     r = 10
>>     break
>>   if r is None: something
>>   else: return r
>> 

To bonono, not Steve:

So if a function should religiously have only one exit point why does the 
example you give have two exit points? i.e. the 'return r', and the implied 
'return None' if you execute the 'something' branch.

> Well, I'm happy in this instance that practicality beats purity, since 
> the above is not only ugly in the extreme it's also far harder to read.
> 
> What are the claimed advantages for a single exit point? I'd have 
> thought it was pretty obvious the eight-line version you gave is far 
> more likely to contain errors than Mike's three-line version, wouldn't 
> you agree?
> 
Arguments include: any cleanup code you need when returning from a function 
is all in one place (mostly applicable to languages where you have to do 
your own memory management---see the recent AST discussion on the python 
dev list); or it stops you accidentally forgetting to return a value (as 
demonstrated above :^) )

In practice it is impossible to write code in Python (or most 
languages) with only one return point from a function: any line could throw 
an exception which is effectively another return point, so the cleanup has 
to be done properly anyway.



More information about the Python-list mailing list