4.4. Basic Debugging

4.4.1. Run in the console

  • Execute cell

  • Run File in the console

4.4.2. print

DATA = ['a', 'b', 'c', [1, 2, 3]]

for element in DATA:
    print(element)
    # a
    # b
    # c
    # [1, 2, 3]

4.4.3. Use cases

One element tuple (ADMINISTRATORS) has comma at the end:

## Content of the ``settings.py`` file
ADMINISTRATORS = 'mwatney@nasa.gov',


## Content of the ``script.py`` file
from settings import ADMINISTRATORS

for admin in ADMINISTRATORS:
    print(admin)

# mwatney@nasa.gov

Problem with missing coma for ADMINISTRATORS tuple:

## Content of the ``settings.py`` file
ADMINISTRATORS = 'mwatney@nasa.gov'


## Content of the ``script.py`` file
from settings import ADMINISTRATORS

for admin in ADMINISTRATORS:
    print(admin)

# m
# w
# a
# t
# n
# e
# y
# @
# n
# a
# s
# a
# .
# g
# o
# v

4.4.4. pprint

from pprint import pprint

pprint(...)
import json
from pprint import pprint

DATA = '{"contacts": [{"id": 1, "created": "2018-06-13T09:57:55.405Z", "modified": "2018-06-13T10:16:13.975Z", "reporter_id": 1, "is_deleted": false, "firstname": "Mark", "lastname": "Watney", "birthdate": "1969-07-24", "email": "mwatney@nasa.gov", "bio": "", "image": "mwatney.jpg", "status": null, "gender": null}, {"id": 2, "created": "2018-06-13T10:26:46.948Z", "modified": "2018-06-13T10:26:46.948Z", "reporter_id": 1, "is_deleted": false, "firstname": "Melissa", "lastname": "Lewis", "birthdate": null, "email": null, "bio": "", "image": "", "status": null, "gender": null}, {"id": 3, "created": "2018-06-13T10:26:55.820Z", "modified": "2018-06-13T10:26:55.820Z", "reporter_id": 1, "is_deleted": false, "firstname": "Rick", "lastname": "Martinez", "birthdate": null, "email": null, "bio": "", "image": "", "status": null, "gender": null}, {"id": 15, "created": "2018-06-13T14:34:42.353Z", "modified": "2018-06-13T14:34:43.638Z", "reporter_id": null, "is_deleted": false, "firstname": "Alex", "lastname": "Vogel", "birthdate": null, "email": null, "bio": null, "image": "", "status": null, "gender": null}]}'

data = json.loads(DATA)
pprint(data)
pprint(globals())
from pprint import pprint

print(globals())
pprint(globals())

def hello(a, b, text='My name...'):
    firstname = 'José'
    lastname = 'Jiménez'
    pprint(locals())
    return locals()


hello(1, 2)

4.4.5. pformat

from pprint import pformat


class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return pformat(self.__dict__, indent=1, width=120, compact=False)

p = Point(1, 2)

repr(p)
# <__main__.Point object at 0x10378a470>

str(p)
# {'x': 1, 'y': 2}

print(p)
# {'x': 1, 'y': 2}

4.4.6. locals()

def hello(a, b, text='My name...'):
    firstname = 'José'
    lastname = 'Jiménez'
    my_vars = locals()
    del my_vars['text']
    return my_vars

4.4.7. Using debugger in IDE

4.4.8. Setting Break Points

4.4.9. Inspecting variable values

4.4.10. Resume Program

4.4.11. json.tool

$ curl -s http://localhost:8000/contact/api/
{"contacts": [{"id": 1, "created": "2018-06-13T09:57:55.405Z", "modified": "2018-06-13T10:16:13.975Z", "reporter_id": 1, "is_deleted": false, "firstname": "José", "lastname": "Jiménez", "birthdate": "1969-07-24", "email": "jose.jimenez@nasa.gov", "bio": "", "image": "33950257662_d7561fb140_o.jpg", "status": null, "gender": null}, {"id": 2, "created": "2018-06-13T10:26:46.948Z", "modified": "2018-06-13T10:26:46.948Z", "reporter_id": 1, "is_deleted": false, "firstname": "Mark", "lastname": "Watney", "birthdate": null, "email": null, "bio": "", "image": "", "status": null, "gender": null}, {"id": 3, "created": "2018-06-13T10:26:55.820Z", "modified": "2018-06-13T10:26:55.820Z", "reporter_id": 1, "is_deleted": false, "firstname": "Иван", "lastname": "Иванович", "birthdate": null, "email": null, "bio": "", "image": "", "status": null, "gender": null}]}
$ curl -s http://localhost:8000/contact/api/ |python -m json.tool
{
    "contacts": [
        {
            "id": 1,
            "created": "2018-06-13T09:57:55.405Z",
            "modified": "2018-06-13T10:16:13.975Z",
            "reporter_id": 1,
            "is_deleted": false,
            "firstname": "José",
            "lastname": "Jiménez",
            "birthdate": "1969-07-24",
            "email": "jose.jimenez@nasa.gov",
            "bio": "",
            "image": "33950257662_d7561fb140_o.jpg",
            "status": null,
            "gender": null
        },
        {
            "id": 2,
            "created": "2018-06-13T10:26:46.948Z",
            "modified": "2018-06-13T10:26:46.948Z",
            "reporter_id": 1,
            "is_deleted": false,
            "firstname": "Mark",
            "lastname": "Watney",
            "birthdate": null,
            "email": null,
            "bio": "",
            "image": "",
            "status": null,
            "gender": null
        },
        {
            "id": 3,
            "created": "2018-06-13T10:26:55.820Z",
            "modified": "2018-06-13T10:26:55.820Z",
            "reporter_id": 1,
            "is_deleted": false,
            "firstname": "Иван",
            "lastname": "Иванович",
            "birthdate": null,
            "email": null,
            "bio": "",
            "image": "",
            "status": null,
            "gender": null
        },
    ]
}

4.4.12. Using pdb

print('José Jiménez')
import pdb; pdb.set_trace()
print('Mark Watney')

4.4.13. breakpoint()

print('José Jiménez')
breakpoint()
print('Mark Watney')
  • sys.breakpointhook()

  • sys.__breakpointhook__

  • By default, sys.breakpointhook() implements the actual importing and entry into pdb.set_trace().

  • It can be set to a different function to change the debugger that breakpoint() enters.

os.environ['PYTHONBREAKPOINT'] = 'foo.bar.baz'
breakpoint()    # Imports foo.bar and calls foo.bar.baz()

4.4.14. code.interact()

  • Halt code execution and open REPL with current state

import code
code.interact(local=locals())

4.4.15. Using debugger in IDE

4.4.16. Break Point

4.4.17. View Breakpoints

4.4.18. Mute Breakpoints

4.4.19. Poruszanie się

4.4.20. Step Over

4.4.21. Step Into My Code

4.4.22. Force Step Into

4.4.23. Show Execution Point

4.4.24. Step Out

4.4.25. Run to Cursor

4.4.26. Resume Program

4.4.27. New Watch

4.4.28. Frames

4.4.29. Previous Frame

4.4.30. Next Frame

4.4.31. Threads

4.4.32. Scope

4.4.33. Special Variables

  • __file__

  • __name__

  • __builtins__

  • __doc__

  • __loader__

  • __spec__

  • __package__

4.4.34. Moduły

4.4.35. Stałe

4.4.36. Zmienne

4.4.37. Wartości funkcji

4.4.38. Debugging i Wątki

4.4.39. Debugging i Procesy

4.4.40. Debugging aplikacji sieciowych

import logging

logging.getLogger('requests').setLevel(logging.DEBUG)

4.4.41. Wyciszanie logowania

import logging

logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime).19s] [%(levelname)s] %(message)s')

logging.getLogger('requests').setLevel(logging.WARNING)
log = logging.getLogger(__name__)

log.debug('This is my debug message')

4.4.42. Assignments

"""
* Assignment: Own `doctest`
* Complexity: easy
* Lines of code: 60 lines
* Time: 21 min

English:
    1. For code from listing
    2. Write your own simplified implementation of `doctest`
    3. For simplicity, assume that only one line will always be returned (directly below the test)
    4. Run doctests - all must succeed

Polish:
    1. Dla kodu z listingu
    2. Napisz własną uproszczoną implementację `doctest`
    3. Dla uproszczenia przyjmij, że zwracana zawsze będzie tylko jedna linia (bezpośrednio poniżej testu)
    4. Uruchom doctesty - wszystkie muszą się powieść
"""

class Astronaut:
    """
    New Astronaut
    """

    def __init__(self, name):
        self.name = name

    def say_hello(self, lang='en'):
        """
        prints greeting according to the language

        >>> Astronaut(name='José Jiménez').say_hello(lang='es')
        '¡hola José Jiménez!'

        >>> Astronaut(name='Pan Twardowski').say_hello(lang='pl')
        'Witaj Pan Twardowski!'
        """
        if lang == 'en':
            return f'hello {self.name}'
        elif lang == 'es':
            return f'¡hola {self.name}!'
        elif lang == 'pl':
            return f'Witaj {self.name}!'
        else:
            return f'hello {self.name}!'