About reading Python code

Stargaming stargaming at gmail.com
Mon Mar 17 01:54:42 EDT 2008


On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote:

> Hello. I wonder what's the effective way of figuring out how a piece of
> python code works.

If your Python code is well-written, it should be easy figuring out what 
it means by just reading it. For more complex programs, of course, this 
method can fail.

> With C I often find it very useful to be able to run
> the code in step mode and set breakpoints in a debugger so I can watch
> how the it executes, how the data change and how the code jumps from one
> function to another. But with Python, the debugger is a little
> primitive. The default IDLE doesn't even allow me to set a breakpoint.
> When the code is long, I am often lost in it.

IDLE is just, well, a batteries-included editor. There are many people 
(me included) who do *not* like it because it's so weak and doesn't have 
any real uses cases if your programs get sufficiently complex (because 
IDLE itself is sufficiently primitive).

You might be interested in *real* debuggers, such as the Python Debugger 
`PDB <http://docs.python.org/lib/module-pdb.html>`_. If you don't find 
its usage obvious, a quick google search just turned up a nice `tutorial 
<http://www.ferg.org/papers/debugging_in_python.html>`_.

You might find the `Python Profilers <http://docs.python.org/lib/
profile.html>`_ particularly interesting, `profile` for finding out which 
function sucks up the most calls/time, `trace` for more sophisticated 
stuff.
`pythontracer <http://code.google.com/p/pythontracer/>` sounds like a 
good combination of both.

> So I'm curious how to read code effectively. I agree that python code is
> clear, but when it becomes long, reading it can still be a hard work.

A common practice is just inserting `print` statements since it's so 
easy. If you think your debugging isn't temporary but could be useful and 
will be enabled every now and then, you could also use the `logging 
module <http://docs.python.org/lib/module-logging.html>`_ with the 
``DEBUG`` level.

There was a blog post recently about how to do this `generically for 
functions <http://wordaligned.org/articles/echo>`_.

> BTW. I think this problem also exists in other script languages.

FWIW, I think it's particularly easier in scripting languages to 
implement all kinds of tracing (apart from debugging, which is rather 
unpopular in Python) because you have one *extra* level (the interpreter) 
between your machine and your code.

HTH,
Stargaming



More information about the Python-list mailing list