A friend of mine (another Andy!) started playing with Raspberry Pis about a year or so ago, and has set up his own code club to teach local kids. I’ve seen his videos of programmable robotic arms which looked very cool, and, being the geek that I am, I asked him if I could have a look at his code.
As I read it, I was reminded of the way I did things when I first started (no criticism of Andy at all!). I thought it would make an interesting blog series to look at the top five things that I do (or try to do!) differently now, moving from a beginner hacking around for fun to writing code professionally for paying customers.
So here are my top five things to improve your coding (in no particular order):
1. Document your code (automatically)
2. Write Object Oriented code
3. Get acquainted with useful packages
4. Write tests for your code
5. Use a version control system
Let’s start with documentation. One of the first things you learn when coding in a new language is writing comments. Comments are very important for reminding yourself and helping others what your code does, and if you know python, you’ll know comments follow a ‘#’ symbol! It’s good practice to write a one-liner explaining any non-trivial code, but when you are giving an overview description of a function a beginner might do this:
# This function takes two integers # calculates the product # and also prints the calculation # usage: multiply(2,4) def multiply(a,b) ans = a * b print str(a) + " x " + str(b) + " = " + str(ans)
That’s a great way to start, but when you are writing code that is going to be read and used by others, you can write comments in a way that helps you automatically create documentation, using the magic of python docstrings! Basically, a docstring is a multi line comment at the start of your function, enclosed in triple quotes. It is picked up by various python documentation packages which make up a nicely formatted html page to document your code. Of course you can continue to add single line comments too…
def multiply(a,b) """ Calculates the product of the two values supplied and prints the answer """ ans = a * b # remember to convert integers to strings before attempting to concat print str(a) + " x " + str(b) + " = " + str(ans)
You can read the Python Enhancement Proposal PEP257 (basically a specification) to find out exactly how you should write these docstrings, but for now, let’s also look at how to auto-generate some documentation from our ‘docstringed’ code.
I haven’t had a chance to play with Sphinx yet, but it seems to be the most popular python documentation generator. It does require you to do some setup but it does mean you have flexibility in how your documentation is produced.
For simplicity, PyDoc is unbeatable. Just pass the name of the python file your want to document (without the .py extension), and it will write an html file for you, based on your docsctrings:
pydoc -w helloworld