common practice for creating utility functions?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon May 15 19:43:41 EDT 2006


John Salerno a écrit :
> Just a quickie for today: Is it common (and also preferred, which are 
> two different things!) to create a function that has the sole job of 
> calling another function?

(pasted):
 > def convert_quote(quote):
 >     return make_code(quote)
 >
 > Or does it not make sense to have a function just call another function?

The only use case I can think of for this extra level of indirection 
would be to isolate your code from an implementation detail that may 
change later. But since it's quite easy to do so by just binding the 
original function to a new name, your example's sole result is to slow 
down your program.

It may also happen that you find yourself in such a situation due to 
heavy refactoring, and cannot immediatly get rid of convert_quote 
without breaking client code, but then again, the Right Thing (tm) to do 
would be to alias it:

# def convert_quote(quote):
#     return make_code(quote)
convert_quote = make_quote

So to answer your question, it's certainly not prefered, and hopefully 
very uncommon !-)


> Example: for fun and exercise, I'm creating a program that takes a quote 
> and converts it into a cryptogram. Right now I have four functions:
> 
> convert_quote -- the main function that starts it all
> make_code -- makes and returns the cryptogram
> make_set -- called from make_code, converts the quote into a set so each 
> letter gets only one coded letter
> test_sets -- makes sure a letter isn't assigned to itself
> 
> So my first question is this: should I make a Cryptogram class for this, 
> or are functions fine?

classes are useful to maintain state. If you don't have a state to 
maintain, you probably don't need a class !-)

Note BTW that Python functions are objects (instances of class 
function), and that Python let you write your own callables (just make 
your class implement the __call__() magic method).

My 2 cents



More information about the Python-list mailing list