pythonrdebuggingdata-science

R's browser() equivalent in Python


The title says it all. When you are working R and using RStudio, its really easy and simple to debug something by dropping a browser() call anywhere in your code and seeing what goes wrong. Is there a way to do that with Python? I'm slowly getting very sick of print statement debugging.


Solution

  • It looks like you are looking for ipdb

    The basic usage is to set:

    import ipdb
    ipdb.set_trace()
    

    in your code to explore; this will take you right to that part of code, so you can explore all the variables at that point.

    For your specific use case: "Would it be a setting in my Console so that it Opens pdb right before something crashes" (a comment to another answer), you can use context manager: launch_ipdb_on_exception

    For example:

    from ipdb import launch_ipdb_on_exception
    
    def silly():
        my_list = [1,2,3]
        for i in xrange(4):
            print my_list[i]
    
    if __name__ == "__main__":
        with launch_ipdb_on_exception():
            silly()
    

    Will take you to ipdb session:

          5         for i in xrange(4):
    ----> 6             print my_list[i]
          7
    
    ipdb> i
    3