is there any principle when writing python function

Chris Angelico rosuav at gmail.com
Fri Aug 26 21:37:27 EDT 2011


On Sat, Aug 27, 2011 at 11:26 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I say "might be" because I mean it: these arguments have to be weighed up
> against the argument against breaking code out of functions. It's easy to
> imagine an extreme case where there are a billion *tiny* functions, each of
> which does one micro-operation:
>
> def f1(x): return x + 1
> def f2(x): return 3*x
> def f3(x): return f2(f1(x))  # instead of 3*(x+1)

This fails the "give it a decent name" test. Can you name these
functions according to what they do, as opposed to how they do it? For
instance:

def add_flagfall(x): return x + 1  # add a $1 flagfall to the price
def add_tax(x): return 3*x  # this is seriously nasty tax
def real_price(x): return add_tax(add_flagfall(x))  # instead of 3*(x+1)

This would be acceptable, because each micro-operation has real
meaning. I'd prefer to do it as constants rather than functions, but
at least they're justifying their names.

And you're absolutely right about monkey-patching.

ChrisA



More information about the Python-list mailing list