is there any principle when writing python function

Terry Reedy tjreedy at udel.edu
Tue Aug 23 20:19:15 CEST 2011


On 8/23/2011 7:59 AM, smith jack wrote:
> i have heard that function invocation in python is expensive,

That comes into play when chosing between

list2 = map(lambda x: 2*x, list1) # versus
list2 = [2*x for x in list1]

It also comes into play when choosing between looping with recursion 
(function calls) versus looping with iteration (while/for).  In Python, 
the iteration is faster, while some functional languages omit looping 
syntax constructs and perhaps auto-translate some recursion to iteration.

> but makelots of functions are a good design habit in many other languages,

Same for Python, with the exceptions noted above of avoiding trivial 
one-use functions when there is an alternative.

> is there any principle when writing python function?

Same as usual. Functions define new words and create new abstractions 
than encapsulate a unit of computation.

> for example, how many lines should form a function?

1 to many, as long as the 1 is more complex than 2*x, unless the trivial 
function is required for a callback. I doubt the stdlib has many defs 
longer than 100 lines.

Try the following: complex enough that the function call overhead does 
not matter; simple enough to be understood as a unit.

I just came up with the following hypothesis: the complexity of a 
function is related to the number of *different* functions used to 
define it:
     x = a*b + c/d - e**f
is more complex (harder to understand) than
     x = a + b + c + d + e + f

For this purpose, different statememts count as functions (and indeed, 
they translate to bytecode functions. So:
     for i in iterable:
        if f(i):
           print i
is more complex than
     a = 1
     b = 2
     c = 3
     d = 4

People can retain at most about 10 different things in short term 
memory. So perhaps 10 different 'functions' within a function, or at 
least a commented block, is enough.

-- 
Terry Jan Reedy




More information about the Python-list mailing list