is there any principle when writing python function

Mel mwilson at the-wire.com
Tue Aug 23 08:53:49 EDT 2011


smith jack 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?

It's hard to discuss in the abstract.  A function should perform a 
recognizable step in solving the program's problem.  If you prepared to 
write your program by describing each of several operations the program 
would have to perform, then you might go on to plan a function for each of 
the described operations.  The high-level functions can then be analyzed, 
and will probably lead to functions of their own.

Test-driven development encourages smaller functions that give you a better 
granularity of testing.  Even so, the testable functions should each perform 
one meaningful step of a more general problem.

> for example, how many lines should form a function?
Maybe as few as one.

def increase (x, a):
    return x+a

is kind of stupid, but a more complicated line

def expand_template (bitwidth, defs):
	'''Turn Run-Length-Encoded list into bits.'''
	return np.array (sum (([bit]*(count*bitwidth) for count, bit in 
defs), []), np.int8)

is the epitome of intelligence.  I wrote it myself.  Even increase might be 
useful:

def increase (x, a):
    return x + a * application_dependent_quantity

`increase` has become a meaningful operation in the imaginary application 
we're discussing.


For an upper bound, it's harder to say.  If you read to the end of a 
function and can't remember how it started, or what it did in between, it's 
too big.  If you're reading on your favourite screen, and the end and the 
beginning are more than one page-scroll apart, it might be too big.  If it's 
too big, factoring it into sub-steps and making functions of some of those 
sub-steps is the fix.

	Mel.




More information about the Python-list mailing list