return command in a function.

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Sep 28 04:27:58 EDT 2001


David Bolen <db3l at fitlinxx.com> wrote in
news:ulmj07beu.fsf at ctwd0143.fitlinxx.com: 

>> i don't think so, because it's well defined where it's going to;
>> much like break and continue.
>> 
>> a goto could take you anywhere and complicates the 'state' and control
>> flow of the function. 
> 
> It's controversial at least (IMO) because it violates the one entry,
> one exit theory, and can also make it harder to maintain a function
> that may need to perform cleanup of local resources before exit.

In a language that, like Python, makes extensive use of exceptions, you 
already cannot guarantee a single exit point from your function. Using 
return in a controlled way from inside a function doesn't make this worse.

Python handles many cases of cleaning up local resources automatically (by 
deleting them when their reference counts hit zero), and in those few cases 
where you need to do more, or make sure objects are deleted immediately on 
exit even when an exception is thrown you can use try/finally.

My rule of thumb for using return is that it is alright at or near the top 
of a function, and it is alright at or near the bottom of the function, and 
anywhere else the function is too long and should be split up anyway.

It occurs to me that one of the common cases where people use return inside 
a long function in other languages is when the function comprises a large 
switch/case statement. Since Python doesn't have a switch statement, you 
are encouraged to think of other ways to code these situations (e.g.
dictionary lookup/polymorphism/visitor pattern) which result in a lot of 
small functions instead of a monolith.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list