{"id":13595787,"url":"https://github.com/spiside/pdb-tutorial","last_synced_at":"2026-01-28T14:11:23.221Z","repository":{"id":5598501,"uuid":"53524489","full_name":"spiside/pdb-tutorial","owner":"spiside","description":"A simple tutorial about effectively using pdb","archived":false,"fork":false,"pushed_at":"2024-06-06T17:31:47.000Z","size":85,"stargazers_count":864,"open_issues_count":3,"forks_count":102,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-04-09T13:41:45.561Z","etag":null,"topics":["debugger","pdb","python","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spiside.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-09T19:12:21.000Z","updated_at":"2025-04-07T10:24:59.000Z","dependencies_parsed_at":"2024-01-16T22:20:03.402Z","dependency_job_id":"ab6f08f7-e860-4d3d-b533-9148b3868885","html_url":"https://github.com/spiside/pdb-tutorial","commit_stats":{"total_commits":17,"total_committers":7,"mean_commits":"2.4285714285714284","dds":0.5294117647058824,"last_synced_commit":"c1d3a9c634dcf3d8d730f209110ce6f133b74d6f"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/spiside/pdb-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spiside%2Fpdb-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spiside%2Fpdb-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spiside%2Fpdb-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spiside%2Fpdb-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spiside","download_url":"https://codeload.github.com/spiside/pdb-tutorial/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spiside%2Fpdb-tutorial/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28846058,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-28T13:02:32.985Z","status":"ssl_error","status_checked_at":"2026-01-28T13:02:04.945Z","response_time":57,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["debugger","pdb","python","tutorial"],"created_at":"2024-08-01T16:01:57.617Z","updated_at":"2026-01-28T14:11:23.200Z","avatar_url":"https://github.com/spiside.png","language":"Python","readme":"# `pdb` Tutorial\n\nThe purpose of this tutorial is to teach you the basics of `pdb`, the **P**ython **D**e**B**ugger for [Python2](https://docs.python.org/2/library/pdb.html)\nand [Python3](https://docs.python.org/3/library/pdb.html).\nIt will also include some helpful tricks to make your debugging sessions a lot less stressful.\n\n--- \n\n#### Other translations\n\nThe tutorial is written in english, but there are other translations available with help\nfrom the Python community:\n\n- [Korean](https://github.com/mingrammer/pdb-tutorial)\n- [Chinese](https://github.com/MartinLwx/pdb-tutorial)\n\nIf you would like to see another other translation, or are interested in helping out with translating the tutorial,\nfeel free to add to the [ongoing issues thread](https://github.com/spiside/pdb-tutorial/issues/9).\n\n---\n\n\nThe tutorial works best if you use Python 2.7 or Python 3.4 and I will highlight the\ndifferences between the two versions if a `pdb`\ncommand differs. To check what version of python you're using, type the following in your terminal:\n\n```shell\npython --version\n```\n\nNow that you know your version, let's get to it!\n\n\n## What is the purpose of a debugger?\n\nBefore jumping into the code, we should have a brief discussion about the importance of debugging and using\na debugging tool. For me, these three points highlight the importance of a debugger.\n\nWith a debugger, you can:\n* Explore the state of a running program\n* Test implementation code before applying it\n* Follow the program's execution logic\n\nUsing a debugger, you can set a [breakpoint](https://en.wikipedia.org/wiki/Breakpoint) at any point of\nyour program to stop it and apply the three points above. Debuggers are very powerful tools and they\ncan speed up the debugging process a lot faster than using simple `print()` statements everywhere.\n\nFor those of you who are veteran programmers, you might agree with me that there is a\ncorrelation between the best programmers and the ones that know how to debug effectively. By debugging\neffectively, I mean being able to diagnose a problem and then treat the error with minimal difficulty. \nUsing a debugger and learning how to use it properly will help you become an effective debugger. It will\ntake some time before you feel comfortable navigating around in a debugging environment but the purpose\nof this tutorial is to get your feet wet before you start using `pdb` in your own code base!\n\n\n## Playing the Game\n\nSo we already talked about the purpose of a debugger and now it's time to see it in action. First, you\nshould clone this repo if you haven't already done so. If you don't have `git` installed, I recommend using\nit (or some version of source control) and you can find out details on how to install `git` [here](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git).\nOnce you have `git` installed, clone the repo by entering the following in your terminal:\n\n```shell\ngit clone https://github.com/spiside/pdb-tutorial\n```\n\n**NB**: If that didn't work for you, you should follow Github's [cloning tutorial](https://help.github.com/articles/cloning-a-repository/).\n\nNow that you have the repo cloned, let's navigate to the root of the project and take a look at the instructions given:\n\n```shell\ncd /path/to/pdb-tutorial\n```\n\n`file: instructions.txt`\n```\nYour boss has given you the following project to fix for a client. It's supposed to be a simple dice\ngame where the objective of the game is to correctly add up the values of the dice for 6 consecutive turns.\n\nThe issue is that a former programmer worked on it and didn't know how to debug effectively.\nIt's now up to you to fix the errors and finally make the game playable.\n\nTo play the game you must run the main.py file.\n```\n\nSeems easy enough! To begin, let's try playing the game to see what's wrong. To run the program, type the following in your\nterminal:\n\n```shell\npython main.py\n``` \n\nYou should see something like this:\n\n```\nAdd the values of the dice\nIt's really that easy\nWhat are you doing with your life.\nRound 1\n\n---------\n|*      |\n|       |\n|      *|\n---------\n---------\n|*      |\n|       |\n|      *|\n---------\n---------\n|*     *|\n|       |\n|*     *|\n---------\n---------\n|*     *|\n|       |\n|*     *|\n---------\n---------\n|*     *|\n|   *   |\n|*     *|\n---------\nSigh. What is your guess?: \n```\n\nSeems like the previous programmer had a sense of...humor? Nonetheless, let's enter 17 (since that is the total value of the dice).\n\n```\nSigh. What is your guess?: 17\nSorry that's wrong\nThe answer is: 5\nLike seriously, how could you mess that up\nWins: 0 Loses 1\nWould you like to play again?[Y/n]: \n```\n\nWeird. It said the answer is 5 but that's clearly wrong... Alright, maybe the dice addition is wrong but let's play the game again to\nfigure it out. Looks like the prompt to play again is `'Y'` so let's enter that now.\n\n```\nWould you like to play again?[Y/n]: Y\nTraceback (most recent call last):\n  File \"main.py\", line 12, in \u003cmodule\u003e\n    main()\n  File \"main.py\", line 8, in main\n    GameRunner.run()\n  File \"/Users/Development/pdb-tutorial/dicegame/runner.py\", line 62, in run\n    i_just_throw_an_exception()\n  File \"/Users/Development/pdb-tutorial/dicegame/utils.py\", line 13, in i_just_throw_an_exception\n    raise UnnecessaryError(\"You actually called this function...\")\ndicegame.utils.UnnecessaryError: You actually called this function...\n```\n\nOk weird, there was an exception that was thrown even though we used what was supposed to be a valid input. I think it's safe to\nsay that the program is broken so let's start the debugging process! \n\n\n## PDB 101: Intro to `pdb`\n\nIt's time to finally work with python's very own debugger `pdb`. The debugger is included in python's standard library and we\nuse it the same way we would with any python library. First, we have to import the `pdb` module and then call one of its methods\nto add a debugging breakpoint in the program. The conventional way to do this is to add the import **and** call the method at the same line you\nwould like to stop at. This is the full statement you would want to include:\n\n```python\nimport pdb; pdb.set_trace()\n```\n\nStarting from version 3.7: The built-in function `breakpoint()` can be used instead of using `import pdb; pdb.set_trace()`\n\n```python\nbreakpoint()\n```\n\nThe methods [`set_trace()`](https://docs.python.org/3/library/pdb.html#pdb.set_trace) and [`breakpoint()`](https://docs.python.org/3/library/functions.html#breakpoint) hard code a breakpoint\nwhere the method was called. Let's use the `set_trace()` method for this tutorial since it is supported in all python versions. Let's try it now by opening up the `main.py` file and adding the breakpoint\non line 8:\n\n`file: main.py` \n```python\nfrom dicegame.runner import GameRunner\n\n\ndef main():\n    print(\"Add the values of the dice\")\n    print(\"It's really that easy\")\n    print(\"What are you doing with your life.\")\n    import pdb; pdb.set_trace() # add pdb here\n    GameRunner.run()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\nCool, now let's try to run `main.py` again and see what happens.\n\n```shell\npython main.py\n```\n```\nAdd the values of the dice\nIt's really that easy\nWhat are you doing with your life.\n\u003e /Users/Development/pdb-tutorial/main.py(9)main()\n-\u003e GameRunner.run()\n(Pdb) \n```\n\nThere we go! We are now in the middle of the running program and we can start poking around. I think the first issue we should\nsolve is the proper summation of the dice values.\n\nIf you are familiar with Python's interpreter, a lot of that knowledge can be transferred to the `pdb` debugger. However, there will be\na couple gotchas that we will get to in the advanced section. Regardless, let's learn a couple commands that will help us solve the\naddition issue.\n\n\n## The 5 `pdb` commands that will leave you \"speechless\"\n\nTaken directly from the `pdb` documentation, these are the five commands that, once you learn them, you won't know how you lived\nwithout them.\n\n1. `l(ist)` - Displays 11 lines around the current line or continue the previous listing.\n2. `s(tep)` - Execute the current line, stop at the first possible occasion.\n3. `n(ext)` - Continue execution until the next line in the current function is reached or it returns.\n4. `b(reak)` - Set a breakpoint (depending on the argument provided).\n5. `r(eturn)` - Continue execution until the current function returns.\n\nNotice that there are brackets around the last part of every keyword. The brackets indicate that the rest of the word is _optional_ when\nusing the command prompt for `pdb`. This saves typing but a major gotcha is if you have a variable name such as `l` or `n`, then the\n`pdb` command takes precedence. That is, say you have a variable named `c` in your program and you want to know the value of `c`. Well,\nif you type `c` in `pdb`, you will actually be issuing the `c(ontinue)` keyword which executes the program and only stops if it encounters\na break point!\n\n**NB**: I, and many other programmers, discourage the use of short variable names such as `a`, `b`, `gme`, etc. These carry no meaning\nand will confuse other people reading your code. I'm only demonstrating the issues you may encounter with `pdb` in the presence of\nshortened variable names.\n\n**NNB**: Another helpful tool is the following:\n`h(elp) - Without argument, print the list of available commands. With a command as an argument, print help about that command.`\n\nFor the rest of the tutorial, I will be using the shortened version of the commands and if I use a command that I have not introduced\nhere, I will explain what it does. So, let's begin with the first one.\n\n### 1. l(ist) a.k.a. I'm too lazy to open the file containing the source code\n\n```\nl(ist) [first [,last]]\n    List source code for the current file. Without arguments, list 11 lines around the current line\n    or continue the previous listing. With one argument, list 11 lines starting at that line.\n    With two arguments, list the given range; if the second argument is less than the first, it is a count.\n```\n\n**NB**: The above description was generated by calling `help` on `list`. To get the same output, in the `pdb` REPL type `help l`.\n\nUsing `list`, we can examine the source code of the current file we are in. The arguments for `list` lets you specify a given range\nof lines you wish to see which can be helpful if you are in some weird 3rd party package and you are trying to figure out why they\ncan't get string encoding working _true story_.\n\n**NB**: In Python 3.2 and above, you can type `ll` (long list) which shows you source code for the current function or frame. I use\nthis all the time instead of `l` since it's much better knowing which function you are in than an arbitrary 11 lines around your\ncurrent position.\n\nLet's try using `l` now. In your already open `pdb` prompt, type in `l` and look at the output:\n\n```\n(Pdb) l\n  4     def main():\n  5         print(\"Add the values of the dice\")\n  6         print(\"It's really that easy\")\n  7         print(\"What are you doing with your life.\")\n  8         import pdb; pdb.set_trace()\n  9  -\u003e     GameRunner.run()\n 10     \n 11     \n 12     if __name__ == \"__main__\":\n 13         main()\n[EOF]\n``` \n\nIf we want to see the whole file, we can call the list function with the range 1 to 13 like so:\n\n```\n(Pdb) l 1, 13\n  1     from dicegame.runner import GameRunner\n  2     \n  3     \n  4     def main():\n  5         print(\"Add the values of the dice\")\n  6         print(\"It's really that easy\")\n  7         print(\"What are you doing with your life.\")\n  8         import pdb; pdb.set_trace()\n  9  -\u003e     GameRunner.run()\n 10     \n 11     \n 12     if __name__ == \"__main__\":\n 13         main()\n```\n\nUnfortunately, we don't get that much information from this file alone but we do see that it is calling the `run()` method of the `GameRunner`\nclass. At this point, you might be thinking, \"Awesome, I'll just set a `pdb` in the run method in the `dicegame/runner.py` file !\" That will\nwork, but there's an even easier way using the `step` command we will discuss next.\n\n### 2. `s(tep)` a.k.a let's see what this method does...\n\n```\ns(tep)\n    Execute the current line, stop at the first possible occasion\n    (either in a function that is called or in the current\n    function).\n```\n\nYour current line of execution should still be on `:9` and you can tell the current line by looking at the `-\u003e` outputted by the `list` command. \nLet's call the `step` command and see what happens.\n\n```\n(Pdb) s\n--Call--\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(21)run()\n-\u003e @classmethod\n```\n\nNice! We're currently in the `runner.py` file on line 21 which we can tell from this line:\n`\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(21)run()`.\nThe problem is, we don't have much context so run the `list` command to checkout the method.\n\n```\n(Pdb) l\n 16             total = 0\n 17             for die in self.dice:\n 18                 total += 1\n 19             return total\n 20     \n 21  -\u003e     @classmethod\n 22         def run(cls):\n 23             # Probably counts wins or something.\n 24             # Great variable name, 10/10.\n 25             c = 0\n 26             while True:\n```\n\nAwesome! Now we have some more context on the `run()` method but we are currently on `:21`. Let's `step` in one more time so that we enter the method itself and\nthen run the list command to see our current position.\n\n```\n(Pdb) s\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(25)run()\n-\u003e c = 0\n(Pdb) l\n 20     \n 21         @classmethod\n 22         def run(cls):\n 23             # Probably counts wins or something.\n 24             # Great variable name, 10/10.\n 25  -\u003e         c = 0\n 26             while True:\n 27                 runner = cls()\n 28     \n 29                 print(\"Round {}\\n\".format(runner.round))\n 30  \n```\n\nAs we can see, we are on a terribly named `c` variable that will cause us a major issue if we try to call it (remember the comment from earlier regarding the\n`c(ontinue)` command). We are just before the `while` loop so let's enter the loop and see what else we can uncover.\n\n### 3. `n(ext)` a.k.a I hope this current line doesn't throw an exception\n\n```\nn(ext)\n    Continue execution until the next line in the current function\n    is reached or it returns.\n```\n\nFrom the current line, type the `n(ext)` command followed by `list` (notice a pattern) and let's observe what happens.\n\n**NB**: `n(ext)` allows you to skip over function calls while `s(tep)` allows you to step into a function call and pause at the first line of the called function.\n\n```\n(Pdb) n\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(27)run()\n-\u003e while True:\n(Pdb) l\n 21         @classmethod\n 22         def run(cls):\n 23             # Probably counts wins or something.\n 24             # Great variable name, 10/10.\n 25             c = 0\n 26  -\u003e         while True:\n 27                 runner = cls()\n 28     \n 29                 print(\"Round {}\\n\".format(runner.round))\n 30     \n 31                 for die in runner.dice:\n```\n\nNow our current line on the `while True` statement! We can keep calling `next` indefinitely until the program throws an exception or terminates. Call `next` 3 more\ntimes to get to the `for` loop and then follow up `next` with `list`.\n\n```\n(Pdb) n\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(27)run()\n-\u003e runner = cls()\n(Pdb) n\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(29)run()\n-\u003e print(\"Round {}\\n\".format(runner.round))\n(Pdb) n\nRound 1\n\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(31)run()\n-\u003e for die in runner.dice:\n(Pdb) l\n 26             while True:\n 27                 runner = cls()\n 28     \n 29                 print(\"Round {}\\n\".format(runner.round))\n 30     \n 31  -\u003e             for die in runner.dice:\n 32                     print(die.show())\n 33     \n 34                 guess = input(\"Sigh. What is your guess?: \")\n 35                 guess = int(guess)\n```\n\nAt this current point, if you continue to type the `next` command you will then iterate through the `for` loop for the length of the `runner.dice`\nattribute. We can take a look at the length of the `runner.dice` by calling the `len()` function around it in the `pdb` REPL which should return 5.\n\n```\n(Pdb) len(runner.dice)\n5\n```\n\nSince the length is _only_ 5 items, we could iterate through the loop by calling `next` 5 times, but let's say there were 50 items to iterate over, or even 10,000!\nA better option would be to set a break point and then `continue` to that break point instead.\n\n\n### 4. `b(reak)` a.k.a I don't want to type `n` anymore\n\n```\nb(reak) [ ([filename:]lineno | function) [, condition] ]\n    Without argument, list all breaks.\n\n    With a line number argument, set a break at this line in the\n    current file.  With a function name, set a break at the first\n    executable line of that function.  If a second argument is\n    present, it is a string specifying an expression which must\n    evaluate to true before the breakpoint is honored.\n\n    The line number may be prefixed with a filename and a colon,\n    to specify a breakpoint in another file (probably one that\n    hasn't been loaded yet).  The file is searched for on\n    sys.path; the .py suffix may be omitted.\n```\n\nWe're only going to pay attention to the first two paragraphs of `b(reak)`'s description in this tutorial. Like I mentioned in the previous section, we want\nto set a break point past the `for` loop so we can continue to navigate through the `run()` method. Let's stop on `:34` since this has the input function\nwhich will break and wait for a user input anyways. To do this, we can type `b 34` and then `continue` to the break point.\n\n```\n(Pdb) b 34\nBreakpoint 1 at /Users/Development/pdb-tutorial/dicegame/runner.py(34)run()\n(Pdb) c\n\n[...] # prints some dice\n\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(34)run()\n-\u003e guess = input(\"Sigh. What is your guess?: \")\n```\n\nWe can also take a look at the break points that we have set by calling `break` without any arguments.\n\n```\n(Pdb) b\nNum Type         Disp Enb   Where\n1   breakpoint   keep yes   at /Users/Development/pdb-tutorial/dicegame/runner.py:34\n    breakpoint already hit 1 time\n```\n\nTo clear your break points, you can use the `cl(ear)` command followed by the breakpoint number which is found in the leftmost column of the above\noutput. Let's clear the breakpoint now by calling the `clear` command followed by 1.\n\n**NB**: You can also clear all the breakpoints if you don't provide any arguments to the `clear` command.\n\n```\n(Pdb) cl 1\nDeleted breakpoint 1 at /Users/Development/pdb-tutorial/dicegame/runner.py:34\n```\n\nFrom here we can call `next` and execute the `input()` function. Let's just type 10 for our guess and once we are back in the `pdb` REPL, call `list` so we can see\nthe next few lines.\n\n```\n(Pdb) n\nSigh. What is your guess?: 10\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(35)run()\n-\u003e guess = int(guess)\n(Pdb) l\n 30     \n 31                 for die in runner.dice:\n 32                     print(die.show())\n 33     \n 34                 guess = input(\"Sigh. What is your guess?: \")\n 35  -\u003e             guess = int(guess)\n 36     \n 37                 if guess == runner.answer():\n 38                     print(\"Congrats, you can add like a 5 year old...\")\n 39                     runner.wins += 1\n 40                     c += 1\n\n\n``` \n\nRemember that we are trying to find out why our guess wasn't correct on our first playthrough. It seemed like there was an error with the `guess == runner.answer`\nequality condition. We should check to see what the `runner.answer()` method is doing in case there might be an error there. Call `next` and then let's call `step`\nto _step_ into the `runner.answer()` method.\n\n```\n(Pdb) s\n--Call--\n\u003e /Users/spiro/Development/mobify/engineering-meeting/pdb-tutorial/dicegame/runner.py(15)answer()\n-\u003e def answer(self):\n(Pdb) l\n 10         def reset(self):\n 11             self.round = 1\n 12             self.wins = 0\n 13             self.loses = 0\n 14     \n 15  -\u003e     def answer(self):\n 16             total = 0\n 17             for die in self.dice:\n 18                 total += 1\n 19             return total\n 20  \n```\n\nI think I found the issue! On line 18, it doesn't look like the `total` variable is adding up the values of the dice like we want it to. Let's see if we can fix that by\nchecking whether a `die` has an attribute which would contain its value. To get to line 18, you can either set a break point or just call `next` until you\nhit the first iteration. Once you're on `:18`, let's call the `dir()` function on the `die` instance and check what methods and attributes it has.\n\n```\n-\u003e total += 1\n(Pdb) dir(die)\n['__class__', '__delattr__', [...], 'create_dice', 'roll', 'show', 'value']\n``` \n\nThere is a `value` attribute after all! Let's call that and see what returns (remember, this value will probably be different than mine). And just for fun,\nlet's make sure it is equal to the value that the die is showing by calling the `show()` method as well.\n\n```\n(Pdb) die.value\n2\n(Pdb) die.show()\n'---------\\n|*      |\\n|       |\\n|      *|\\n---------'\n```\n\n**NB**: If you want the newline character `\\n` to print as a newline, call `print()` with `die.show()` as its argument.\n\nIt looks like it works as expected and we're ready to fix the answer method. However, some of us may want to continue with the debugging process and catch all the\nerrors in one go. Unfortunately, we are once again stuck in this for loop. You might think to set a break point at `:19` and then call `continue` but there is actually\na better way in this case.\n\n### 5. `r(eturn)` a.k.a. I want to get out of this function\n\n```\nr(eturn)\n    Continue execution until the current function returns.\n```\n\nThe `return` is a great _power user_ command that let's you examine the final outcome of a function. While you could set a breakpoint at the return call, the\n`return` pdb command will help if there are multiple return statements in a single function since it only follows the path of execution for a single return. Let's\ncall the `return` command and get to the end of the function.\n\n```\n(Pdb) r\n--Return--\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(19)answer()-\u003e5\n-\u003e return total\n(Pdb) l\n 14     \n 15         def answer(self):\n 16             total = 0\n 17             for die in self.dice:\n 18                 total += 1\n 19  -\u003e         return total\n 20     \n 21         @classmethod\n 22         def run(cls):\n 23             # Probably counts wins or something.\n 24             # Great variable name, 10/10.\n(Pdb) \n```\n\nTo check the value of the returned `total` variable, you can call `total` here or look at the final value in line below the `--Return--` output. Now, to return back\nto the `run()` method, call the `next` command and you'll be back in your happy place.\n\nAt this point, you can exit the `pdb` debugger by calling `exit()` **OR** `CTRL+D` (same as the Python REPL). With these five commands, you should be able to figure\nout a couple other bugs and then follow along with a bit more advanced `pdb` examples.\n\n\n## Advanced `pdb` topics\n\nHere are a couple advanced `pdb` commands that you can also use.\n\n### The `!` (bang) command\n\n```\n!\n  Execute the (one-line) statement in the context of the current stack frame.\n```\n\nThe bang command (`!`) lets `pdb` know that the following statement will be a Python command and not a `pdb` command. Where this is helpful is in the `run()` method\nwith the `c` variable. Like I mentioned in the beginning of the tutorial, calling `c` in `pdb` will issue the `continue` command. Navigating in your `pdb` REPL, stop\nat `:26` in the `runner.py` file and from that point you can prefix `c` with the `!` command and see what happens. \n\n```\n (Pdb) !c\n 0\n```\n\nWe get the intended result, since `:25` assigned `c = 0`!\n\n### The `commands` command\n\n```\ncommands [bpnumber]\n        (com) ...\n        (com) end\n        (Pdb)\n\n        Specify a list of commands for breakpoint number bpnumber.\n```\n\n`commands` will run python code or pdb commands that you specified whenever the stated breakpoint number is hit. Once you start the `commands` block, the prompt changes to `(com)`. The code/commands you write here function as if you had typed them at the `(Pdb)` prompt after getting to that breakpoint. Writing `end` will terminate the command and the prompt changes back to `(Pdb)` from `(com)`. I have found this of great use when I need to monitor certain variables inside of a loop as I don't need to print the values of the variables repeatedly. Let's see an example. Make sure to be at the root of the project in your terminal and type the following:\n\n```\npython -m pdb main.py\n```\n\nReach line `:8` and `s(tep)` into the `run()` method of the GameRunner class. Then, set up a breakpoint at `:17`.\n```\n\u003e /Users/Development/pdb-tutorial/main.py(8)main()\n-\u003e GameRunner.run()  #This is line 8 in main.py\n(Pdb) s      \n--Call--\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(21)run()\n-\u003e @classmethod \n(Pdb) b 17\nBreakpoint 4 at /Users/Development/pdb-tutorial/dicegame/runner.py:17\n```\nThis sets up the breakpoint, which has been given the number `4`, at the start of the loop inside the `answer()` method which is used to calculate the total values of the dice. Now, let's us use `commands` to print the value of the variable `total` when we hit this breakpoint. \n\n```\n(Pdb) commands 4\n(com) print(f\"The total value as of now is {total}\")\n(com) end\n```\nWe have now set up `commands` for breakpoint number 4 which will execute when we reach this breakpoint. Let us `c(ontinue)` and reach this breakpoint.  \n\n```\n(Pdb) c\n[...] # You will have to guess a number\nThe total value as of now is 0\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(17)answer()\n-\u003e for die in self.dice:\n(Pdb)\n```\n\nWe see that out print statement executed upon reaching this breakpoint. Let's `c(ontinue)` again and see what happens.\n\n```\n(Pdb) c\n[...] \nThe total value as of now is 1\n\u003e /Users/Development/pdb-tutorial/dicegame/runner.py(17)answer()\n-\u003e for die in self.dice:\n(Pdb)\n```\nThe `commands` command executes upon reaching the breakpoint again. You can see how this might be useful especially during loops.\n\n### `pdb` Post Mortem\n\n```\npdb.post_mortem(traceback=None)\n    Enter post-mortem debugging of the given traceback object. If no traceback is given, it uses the one of the exception that is currently being handled\n    (an exception must be being handled if the default is to be used).\n\npdb.pm()\n    Enter post-mortem debugging of the traceback found in sys.last_traceback. \n```\n\nWhile both methods may look the same, `post_mortem() and pm()` differ by the traceback they are given. I commonly use `post_mortem()` in the `except` block.\nHowever, we will cover the `pm()` method since I find it to be a bit more powerful. Let's try and see how this works in practice.\n\nOpen up the python REPL by typing `python` in your shell in the root of this project. From there, let's import the `main` method from the `main` module and import `pdb`\nas well. Play the game until the we get the exception after trying to type `Y` to continue the game.\n\n```\n\u003e\u003e\u003e import pdb\n\u003e\u003e\u003e from main import main\n\u003e\u003e\u003e main()\n[...]\nWould you like to play again?[Y/n]: Y\nTraceback (most recent call last):\n  File \"main.py\", line 12, in \u003cmodule\u003e\n    main()\n  File \"main.py\", line 8, in main\n    GameRunner.run()\n  File \"/Users/Development/pdb-tutorial/dicegame/runner.py\", line 62, in run\n    i_just_throw_an_exception()\n  File \"/Users/Development/pdb-tutorial/dicegame/utils.py\", line 13, in i_just_throw_an_exception\n    raise UnnecessaryError(\"You actually called this function...\")\ndicegame.utils.UnnecessaryError: You actually called this function...\n```\n\nNow, let's call the `pm()` method from the `pdb` module and see what happens.\n\n```\n\u003e\u003e\u003e pdb.pm()\n\u003e /Users/Development/pdb-tutorial/dicegame/utils.py(13)i_just_throw_an_exception()\n-\u003e raise UnnecessaryError(\"You actually called this function...\")\n(Pdb) \n```\n\nLook at that! We recover from the point where the last exception was thrown and are placed in the `pdb` prompt. From here, we can examine the state the program was in\nbefore it crashed which will help you in your investigation.\n\n**NB**: You can also start the `main.py` script using `python -m pdb main.py` and `continue` until an exception is thrown. Python will automatically enter `post_mortem`\nmode at the uncaught exception.\n\n\n## The End\n\nCongrats on making it to the end and thank you for following along in this tutorial! If you have any comments, critiques, or additional advanced examples, I'm open to pull requests.\n\n","funding_links":[],"categories":["Python","课程"],"sub_categories":["介绍和教程"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspiside%2Fpdb-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspiside%2Fpdb-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspiside%2Fpdb-tutorial/lists"}