[Tutor] Souce Debuger

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 3 Nov 2001 15:19:19 -0800 (PST)


On Sat, 3 Nov 2001, Boudewijn Rempt wrote:

> > Is there anything comprable to gdb for python? I want to step through a
> > large program, and cutting and pasting into the interp is a lot of work.
> >
> 
> Finally, there's not much that a well-placed print statement cannot
> tell you :-).


Also, the Python interpreter itself is wonderful when you want to debug
something --- you don't have to cut and paste!  You can "import" your
program as if it were a module, and then test out your functions
individually.  As you make changes to your source code, you can ask Python
to "reload()" your code.


For example, let's say we were debugging a program that tries to figure
out if a word sounds like Klingon or not:

###
## klingon.py
def isSoundingLikeKlingon(name):
    ## If the suffix of the word is guttural, it's probably Klingon.
    if name[-2:] in ('gh', 'pu'):
        return 1
    return 0
###


How can we test this function out?  We can import it:

###
>>> import klingon
>>> klingon.isSoundingLikeKlingon("qa'vIn")
0
>>> klingon.isSoundingLikeKlingon("pagh")
1
###

Ok, this is certainly not accurate at all --- it doesn't even recognize
that "qa'vIn" stands for the word "coffee"!  If we modify klingon.py:


###
def isSoundingLikeKlingon(name):
    ## If the suffix of the word is guttural, it's probably Klingon.
    if name[-2:] in ('gh', 'pu'):
        return 1
    if name[-3:] in ('vIn'):
        return 1
    return 0
###


and save the file, we can go back to where we left off on the interpreter:


###
>>> reload(klingon)
<module 'klingon' from 'klingon.pyc'>
>>> reload(klingon)
<module 'klingon' from 'klingon.py'>
>>> klingon.isSoundingLikeKlingon("qa'vIn")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "klingon.py", line 5, in isSoundingLikeKlingon
    if name[-3:] in ('vIn'):
TypeError: 'in <string>' requires character as left operand
###


Ooops!  I forgot that "('vIn')" doesn't look like a tuple of one element
to Python --- instead, to Python, those parens are there for precedence
sake.  Let me fix that bug:

###
def isSoundingLikeKlingon(name):
    ## If the suffix of the word is guttural, it's probably Klingon.
    if name[-2:] in ('gh', 'pu'):
        return 1
    if name[-3:] in ('vIn',):       ## The trailing comma convinces
                                    ## python to treat ('vIn',) as a
                                    ## tuple of one element.
        return 1
    return 0
###

and try again:

###
>>> reload(klingon)
<module 'klingon' from 'klingon.py'>
>>> klingon.isSoundingLikeKlingon("qa'vIn")
1
###


That's better.  Now I'm going out for a little bit of qa'vIn.  *grin*