Published online by Cambridge University Press: 05 February 2015
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.
To save this book to your Kindle, first ensure [email protected] is added to your Approved Personal Document E-mail List under your Personal Document Settings on the Manage Your Content and Devices page of your Amazon account. Then enter the ‘name’ part of your Kindle email address below. Find out more about saving to your Kindle.
Note you can select to save to either the @free.kindle.com or @kindle.com variations. ‘@free.kindle.com’ emails are free but can only be saved to your device when it is connected to wi-fi. ‘@kindle.com’ emails can be delivered even when you are not connected to wi-fi, but note that service fees apply.
Find out more about the Kindle Personal Document Service.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Dropbox.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Google Drive.