What's the proper style for a library string function?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 19 21:41:40 EDT 2014


On Sat, 19 Jul 2014 10:38:47 -0700, C.D. Reimer wrote:

> Greetings,
> 
> I typically write a Python 2.7 string function in my library like this:
> 
>      def getCompletedTime(start, end): 
>          return "Time completed:", str(end - start)
> 
> And called it like this:
> 
>      print getCompletedTime(start, end)
> 
> Since every Python script I write is executed from the command line, I
> rewrote the string function like this:
> 
>      def getCompletedTime(start, end): 
>           print "Time completed:", str(end - start)
> 
> And call it like this:
> 
>      getCompletedTime(start, end)

In general, I much prefer the first version. The general principle I 
follow is, as much as possible, to separate calculation from display. 
Advantages include:

- You can easily re-use the getCompletedTime function in situations where 
you don't want to display the time, or pass the result on to another 
function for further processing before display.

- It makes automated testing of the functions much easier.

- It makes it easier to vary the type of display. Today you want to print 
to the standard output. Tomorrow you might want to output to a file, or 
display in a GUI window.

- It makes it easier to understand the large-scale structure of your 
code. Seeing "print getCompletedTime(a, b)" makes it pretty clear that 
you are printing the result of the calculation, whereas 
"getCompletedTime(a, b)" does not.



-- 
Steven



More information about the Python-list mailing list