Package: pdbr
pdbrpdbris intended to make the PDB results more colorful. it usesRichlibrary to carry out that.InstallingInstall withpipor your favorite PyPi package manager.pip install pdbrBreakpointIn order to usebreakpoint(), setPYTHONBREAKPOINTwith "pdbr.set_trace"importosos.environ["PYTHONBREAKPOINT"]="pdbr.set_trace"or just import pdbrimportpdbrNew commands(i)nspect / inspectall | iarich.inspectsearch | srcSearch a phrase in the current frame.
In order to repeat the last one, type/character as arg.sqlDisplay value in sql format. Don't forget to installsqlparsepackage.It can be used for Django model queries as follows.>>> sql str(Users.objects.all().query)(syn)tax[ val,lexer ] Displaylexer.(v)arsGet the local variables list as table.varstree | vtGet the local variables list as tree.ConfigConfig is specified insetup.cfgand can be local or global. Local config (current working directory) has precedence over global (default) one. Global config must be located in$XDG_CONFIG_HOME/pdbr/directory.StyleIn order to use Rich's traceback, style, and theme:[pdbr]
style = yellow
use_traceback = True
theme = friendlyAlso customConsoleobject can be assigned to theset_trace.importpdbrfromrich.consoleimportConsolefromrich.styleimportStylefromrich.themeimportThemecustom_theme=Theme({"info":"dim cyan","warning":"magenta","danger":"bold red",})custom_style=Style(color="magenta",bgcolor="yellow",italic=True,)console=Console(theme=custom_theme,style=custom_style)pdbr.set_trace(console=console)Historystore_historysetting is used to keep and reload history, even the prompt is closed and opened again:[pdbr]
...
store_history=.pdbr_historyCeleryIn order to useCeleryremote debugger with pdbr, usecelery_set_traceas below sample. For more information see theCelery user guide.fromceleryimportCeleryapp=Celery('tasks',broker='pyamqp://guest@localhost//')@app.taskdefadd(x,y):importpdbr;pdbr.celery_set_trace()returnx+yTelnetInstead of usingtelnetornc, in terms of using pdbr style,pdbr_telnetcommand can be used.Also in order to activate history and be able to use arrow keys, install and userlwrappackage.rlwrap -H '~/.pdbr_history' pdbr_telnet localhost 6899IPythonpdbrintegrates withIPython.This makes%magicsavailable, for example:(Pdbr)%timeitrange(100)104ns±2.05nsperloop(mean±std.dev.of7runs,10,000,000loopseach)To enableIPythonfeatures, install it separately, or like below:pip install pdbr[ipython]pytestIn order to usepdbrwith pytest--pdbflag, addaddoptssetting in your pytest.ini.[pytest]
addopts: --pdbcls=pdbr:RichPdbsys.excepthookThesys.excepthookis a Python system hook that provides a way to customize the behavior when an unhandled exception occurs. Sincepdbruse  automatic traceback handler feature ofrich, formatting exception print is not necessary ifpdbrmodule is already imported.In order to use post-mortem or perform other debugging features ofpdbr,  overridesys.excepthookwith a function that will act as your custom excepthook:importsysimportpdbrdefcustom_excepthook(exc_type,exc_value,exc_traceback):pdbr.post_mortem(exc_traceback,exc_value)# [Optional] call the original excepthook as wellsys.__excepthook__(exc_type,exc_value,exc_traceback)sys.excepthook=custom_excepthookNow, whenever an unhandled exception occurs,pdbrwill be triggered, allowing you to debug the issue interactively.Context Decoratorpdbr_contextandapdbr_context(asynciocorresponding) can be used aswith statementordecorator. It callspost_mortemiftracebackis not none.frompdbrimportapdbr_context,pdbr_context@pdbr_context()deffoo():...defbar():withpdbr_context():...@apdbr_context()asyncdeffoo():...asyncdefbar():asyncwithapdbr_context():...Django DiscoverRunnerTo being activated the pdb in Django test, changeTEST_RUNNERlike below. Unlike Django (since you are not allowed to use for smaller versions than 3), pdbr runner can be used for version 1.8 and subsequent versions.TEST_RUNNER = "pdbr.runner.PdbrDiscoverRunner"MiddlewaresStarlettefromfastapiimportFastAPIfrompdbr.middlewares.starletteimportPdbrMiddlewareapp=FastAPI()app.add_middleware(PdbrMiddleware,debug=True)@app.get("/")asyncdefmain():1/0return{"message":"Hello World"}DjangoIn order to catch the problematic codes with post mortem, place the middleware class.MIDDLEWARE = (
    ...
    "pdbr.middlewares.django.PdbrMiddleware",
)ShellRunningpdbrcommand in terminal starts anIPythonterminal app instance. Unlike defaultTerminalInteractiveShell, the new shell uses pdbr as debugger class instead ofipdb.%debug magic sampleAs a ScriptIfpdbrcommand is used with an argument, it is invoked as a script anddebugger-commandscan be used with it.# equivalent code: `python -m pdbr -c 'b 5' my_test.py`pdbr-c'b 5'my_test.py>>>Breakpoint1at/my_test.py:5>/my_test.py(3)<module>()12---->3deftest():4foo="foo"15bar="bar"(Pdbr)TerminalDjango shell sampleVscode user snippetTo create or edit your own snippets, selectUser SnippetsunderFile > Preferences(Code > Preferenceson macOS), and then selectpython.json.Place the below snippet in json file forpdbr.{
  ...
  "pdbr": {
        "prefix": "pdbr",
        "body": "import pdbr; pdbr.set_trace()",
        "description": "Code snippet for pdbr debug"
    },
}ForCelerydebug.{
  ...
  "rdbr": {
        "prefix": "rdbr",
        "body": "import pdbr; pdbr.celery_set_trace()",
        "description": "Code snippet for Celery pdbr debug"
    },
}SamplesTraceback