Coding tips
Tim J. Stevens, Wayne Boucher · Cambridge University Press eBooks · 2014
Improving Python code This chapter is concerned with improving Python code and we will illustrate, using short code snippets, various tips that help with speed, memory use and coding clarity. There may be several aspects of a program that we seek to improve, but we can’t necessarily expect to improve all of them all of the time. Often optimisation of a Python program is about compromise; you may make a program run faster at the expense of using more memory. Clarity is an especially important aspect that we will be mindful of when making suggestions, and in general we recommend making code more easily understood over mild improvements in performance. Finding and correcting errors in code can take a long time, sometimes longer than the program took to write in the first place, so keeping the code easy to understand is especially important. A basic programming approach that the authors often follow, and which may be helpful for others, is a three-point plan: Firstly, make the code work: an inelegant program is better than one that doesn’t work. Next do it properly: with a working reference, you can take a step back and criticise your approach. Then make it better: only once your program is working, and the general approach won’t change, is it worth optimising.