Skip to content Skip to sidebar Skip to footer

How To Patch The Python 3 Breakpoint() Builtin?

I wrote a decorator that halts my program with breakpoint() if a critical error happens. def the_breakpoint_dec(func): @functools.wraps(func): async def my_wrapper(func):

Solution 1:

To solve, upgrade your project to 3.8!

I tried to reproduce your scenario in 3.8 and couldn't, the patching worked fine for me. But then when trying with 3.7 and below, the patching stopped working and my program would enter the breakpoint. I have no explanation for this.


Here's a complete running example I coded up. It runs the function_to_test, simulating success and then failure (True/False). As proven by the asserts it only invokes breakpoint() in the failure case, but the test exits cleanly due to our mocked breakpoint() -- at least in 3.8.

from unittest import mock
import functools
import asyncio

def break_if_function_fails(func):
    @functools.wraps(func)
    async def my_wrapper(*args, **kwargs):
        retval = await func(*args, **kwargs)
        return retval if retval else breakpoint()
    return my_wrapper

@break_if_function_fails
async def function_to_test(retval):
    return retval

@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    print('Entering test')
    await function_to_test(True)
    mock_breakpoint.assert_not_called()
    await function_to_test(False)
    mock_breakpoint.assert_called()
    print('Exiting test')

asyncio.run(do_test())

The exact same code does not finish but triggers the breakpoint in 3.7.


If you must stay with 3.7, you can still do

@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    backup_breakpoint = builtins.breakpoint
    builtins.breakpoint = mock_breakpoint
    ...
    builtins.breakpoint = backup_breakpoint

but this is obviously ugly.


Post a Comment for "How To Patch The Python 3 Breakpoint() Builtin?"