is there any principle when writing python function

Roy Smith roy at panix.com
Tue Aug 23 14:55:19 CEST 2011


In article <mailman.346.1314100765.27778.python-list at python.org>,
 smith jack <thinke365 at gmail.com> wrote:

> i have heard that function invocation in python is expensive, but make
> lots of functions are a good design habit in many other languages, so
> is there any principle when writing python function?
> for example, how many lines should form a function?

Enough lines to do what the function needs to do, but no more.

Seriously, break up your program into functions based on logical 
groupings, and whatever makes your code easiest to understand.  When 
you're all done, if your program is too slow, run it under the profiler.  
Use the profiling results to indicate which parts need improvement.

It's very unlikely that function call overhead will be a significant 
issue.  Don't worry about stuff like that unless the profiler shows its 
a bottleneck.  Don't try to guess what's slow.  My guesses are almost 
always wrong.  Yours will be too.

If your program runs fast enough as it is, don't even bother with the 
profiler.  Be happy that you've got something useful and move on to the 
next thing you've got to do.



More information about the Python-list mailing list