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

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Jul 19 20:24:58 CEST 2014


On 19/07/2014 18:38, 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)
>
> The first version is what I'm familiar with having reluctantly learned
> Java at community college, which couldn't afford a Microsoft site
> license for Visual C++ and taught every class in Java. (The Linux
> instructor rebelled against this policy by teaching basic C/C++ and
> shell scripting in his classes.) I recently read an article that Python
> is replacing Java as a teaching language.
>
> The second version is more straight forward but seems less readable
> (i.e., "print getCompletedTime(start, end)" vs. "getCompletedTime(start,
> end)") from the calling script.
>
> Alternatively, I thought about rewriting the string function to accept
> an extra parameter to do either and default to the print statement.
>
>      def getCompletedTime(start, end, type = 'p'):
>          string = "Time completed: " + str(end - start)
>          if type == 'p':
>              print string
>          else:
>              return string
>
> I'm curious as to what the proper Python style would be for this.
>
> Thank you,
>
> Chris Reimer

Besides that I wouldn't write the function on one line, the first.  Once 
you return your data you can do what you want with it.  The second you 
can only write by default to stdout.  The third is really horrible in my 
book, YMMV.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com





More information about the Python-list mailing list