Debugging a function

Jul 31, 2013 at 3:20 AM
I am able to debut a function by inserting a breakpoint and clicking on Start. However, that runs the whole script. On the other hand, when I run a function from the console execution does not stop at the breakpoint. Is there a way to debug a function without running the whole script?

Thanks.
Coordinator
Jul 31, 2013 at 3:59 AM
I'm afraid not, that's not really how Python works. All of the definitions are created by running the script. Generally people will design their scripts to not have any code outside of a function (such as "main") and then call that like:
if __name__ == "__main__":
    main()
That way you can import the file without running any code, but when you run the script directly it will call main(). If you want to test a single function you can change the one called.

For a longer term solution, you may want to invest in unit tests. If you use the standard unittest package then we will detect your tests and you can run or debug them individually.
Jul 31, 2013 at 2:37 PM
Edited Aug 4, 2013 at 8:48 PM
There is another way to debug a function without having to push the Start button, which runs the main module from the beginning. I adapted from the book "Python for Data Analysis" by Wes McKinney.

I put the following in a module called fsf:
from IPython.core.debugger import Pdb # He put this line within each function: it did not work for me

def set_trace():
    Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)

def debug(f, *args, **kwargs):
    pdb = Pdb(color_scheme='Linux')
    return pdb.runcall(f, *args, **kwargs)
To debug a function foo(x, y) starting from the beginning just call
fsf.debug(foo, 3, 4)
To start debugging from a specific line insert the line
fsf.set_trace()
just before the line where you want to start debugging and then call the function.
def foo(x, y):
    x = 1
    fsf.set_trace()
    y = 9
    return x + y

foo(3, 4)