Debugging


In [ ]:
# Get Cheatsheet

In [ ]:
def bad_function():
    
    for i in range(4):
        i += 2
    
    if i == 3:
        print('Finished')

bad_function()

Print


In [ ]:
def meh_function():
    
    for i in range(10):
        print(i)
        i += 2
        print(i)
    
    if i == 10:
        print('Finished')

meh_function()

Logging


In [ ]:
import logging

def main():
    logging.basicConfig(filename='sample.log', level=logging.INFO)
    
    logging.error('Start looping...')
    for item in range(10):
        item += 1
        logging.debug(f'item = {item}')
    logging.debug('...end looping.')
    
    if item == 10:
        print('Finished')
        logging.info('Finished')
        
    logging.info('~ Fin ~')

if __name__ == '__main__':
    main()

Use logging levels.

Level #
Critical 50
Error 40
Warning 30
Info 20
Debug 10
Notset 0

In [ ]:
import logging

def main():
    logging.basicConfig(filename='sample.log',
                        level=logging.INFO)
    
    logging.info('Start looping...')
    for item in range(10):
        item += 1
        logging.debug(f'item = {item}')
    logging.debug('...end looping.')
    
    if item == 10:
        print('Finished')
        logging.debug('Finished')
        
    logging.info('~ Fin ~')

if __name__ == '__main__':
    main()

Too much logging...


In [ ]:
with open('list_of_numbers.txt', 'w') as f:
    for i in range(1, 200000):
        f.write(f'{i},')

In [ ]:
def broken_sum():
    results = []
    with open('list_of_numbers.txt') as f:
        for number in f:
            results.append(number)

    print(f'The sum is {sum(results)}')

broken_sum()

In [ ]:
def still_broken_sum():
    results = []
    with open('list_of_numbers.txt') as f:
        for number in f:
            print(number)
            results.append(number)

    print(f'The sum is {sum(results)}')

still_broken_sum()

Debugging

  • $ python -m pbd file_name.py
  • import pdb; pdb.set_trace()

In [ ]:
def debug_sum():
    results = []
    with open('list_of_numbers.txt') as f:
        import pdb; pdb.set_trace()
        for number in f:
            results.append(number)

    print(f'The sum is {sum(results)}')

debug_sum()

Catching Errors


In [ ]:
def sum_all_the_things():
    results = []
    import pdb; pdb.set_trace()
    with open('list_of_numbers.txt') as f:
        for number in f:
            try:
                results.append(number)
            except ValueError:
                pass
            
    print(f'The sum is {sum(results)}')

sum_all_the_things()

pdb Commands

  • commands<breakpoint number>
  • args to display arguments
  • bt and where show the stace trace
  • (c)ontinue through script
  • move (u)p and (d)own the stack
  • run the (n)ext line of code
  • (s)tep into a function (if possible)

Conditional breakpoint

  • may be disabled
  • may be deleted

pdb++

  • Overlays pdb, still use pdb the normal way.

 


Questions