is there any principle when writing python function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 26 21:26:21 EDT 2011


Chris Angelico wrote:

> On Sat, Aug 27, 2011 at 4:16 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> I can think of at least five reasons apart from re-use why it might be
>> appropriate to pull out code into its own function or method even if it
>> is used in one place only:
> 
> I'm glad you say "might be", because your five reasons aren't always
> reasons for refactoring. I'll play devil's advocate for a moment,
> because discussion is both fun and informative: :)

Naturally :)

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)
...

If spaghetti code (GOTOs tangled all through the code with no structure) is
bad, so is ravioli code (code bundled up into tiny parcels and then thrown
together higgledy-piggledy). Both cases can lead to an unmaintainable mess.
Nobody is arguing that "More Functions Is Always Good". Sensible coders
understand that you should seek a happy medium and not introduce more
functions just for the sake of having More! Functions!.

But I'm not arguing with you, we're in agreement.


One last comment though:

[...]
> Definitely, but it's no value if you make every tiny thing into your
> own function. Sometimes the best way to code is to use lower-level
> functionality directly (not wrapping input() inside raw_select() for
> instance), and letting someone monkey-patch if they want to change
> your code. A judgment call.

I agree on the first part (don't split *everything* into functions) but I
think that the monkey-patch idea is tricky and dangerous in practice. The
first problem is, how do you know what needs to be monkey-patched? You may
not have access to the source code to read, and it may not be as obvious
as "oh, it gets input from the user, so it must be calling input()".

Second, even if you know what to monkey-patch, it's really hard to isolate
the modification to just the method you want. By their nature, monkey-
patches apply globally to the module. And if you patch the builtins module,
they apply *everywhere*.

So while monkey-patching can work, it's tricky to get it right and it should
be left as a last resort.



-- 
Steven




More information about the Python-list mailing list