Organising, debugging and profiling Python code
Following the slides from this morning's session, we will create an animals package.
Please note that with Python 3, implicit relative imports are no longer supported https://www.python.org/dev/peps/pep-0328/
The __init__.py
module should import the Birds
and Mammals
class from the two modules.
Using a python script or an interactive python session outside the package, test your brand new package:
import animals
m = animals.Mammals()
m.printMembers()
b = animals.Birds()
b.printMembers()
import animals
harmless_birds = animals.harmless.Birds()
harmless_birds.printMembers()
dangerous_fish = animals.dangerous.Fish()
dangerous_fish.printMembers()
Investigate buggy code using the pdb or ipdb debugger. Have a look at slides of this mornings's session for help.
Clone this repo (if you have not already done so), go to buggy
and run the main.py
with a debug tracer added to the code. Once you have fixed all errors, the game should correctly add up the values of the dice for 6 consecutive turns.
Ask your neighbour to introduce more bugs into the above (or any other) code examples and try to find the bug using the debugger.
In this section, you should get more familiar with code profiling, in particular with the tools cProfile
, line_profiler
. Have a look at slides from this morning's session to understand what they are doing and when you should use them. Try out profiling both from the command line and using interactive python (e.g. jupyter notebook). If you get Command not found
when running kernprof try searching for it in ~/.local/bin/kernprof
. Alternatively install it using Anaconda/conda (e.g. conda install line_profiler
).
In which line(s) of the script would you start optimizing for speed?
In which line(s) of the script would you start optimizing for speed? (This is one problem from the euler project: https://projecteuler.net/problem=72)
What is the best performance that you achieved with N=250?