Debugging code ================ Debugging code is always a very important part of the development process. In this section, we shall try to give a quick look on how to do it. Post-morten ----------- To debug code once an exception is raised, you can call: .. code:: python %debug You can also toggle automatic postmorten debug with: .. code:: python %pdb Or by starting ipython with the ``--pdb`` option (i.e. ``ipython --pdb``). This way whenever an exception is raised the debugger will be started automatically. Easy breakpoint ---------------- To start the debugger at an specific point in a Python code, you can insert the following inside (a function, for example): .. code:: python import ipdb ipdb.set_trace() Example: .. code:: python def func(x): y = x**2 import ipdb ipdb.set_trace() return y Start debugging on the current terminal ----------------------------------------- You can also start debugging on the current terminal by using: .. code:: python import ipdb ipdb.set_trace("", locals(), globals()) Debugger commands ------------------ There are many command you can run inside a debugger, other than just python code, the most important being: * ``d(own)``: d or down go down in the context. * ``u(p)``: u or up go up in the context. * ``s(tep)``: executes the current line and stops, but if the line is itself another function, the it go inside it. ``n(ext)`` on the other hand always goes to the next line. * ``l(ist)``: show more code around. * ``p``: in general just typing a variable will allow you to see its content, but what if a variable has the same name of a command, then just append p before it, example: ``p next``. Further reading --------------- * https://docs.python.org/3/library/pdb.html