Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break on `pass` in pycharm

In pycharm, I would like to break on a breakpoint that does nothing, during debugging. How can I do this?

For example, I would like to break on the pass statement:

for i in range(999999):
    if i == 6232:
        pass

If I set a breakpoint on pass, the debugger doesn't break there. The closest I've been able to do so far is to make up some unused variable name, and assign it a pointless value, so I can set a breakpoint on that line:

for i in range(999999):
    if i == 6232:
        foobar_unused_variable = "At least I can set a breakpoint on this line."
like image 818
Edward Ned Harvey Avatar asked Dec 04 '17 02:12

Edward Ned Harvey


2 Answers

When the just-in-time compiler compiles your example, it compiles to pass as nothing. In other words, pass is simply a keyword that should be used to tell the compiler that there is no syntax error in what would otherwise be an empty block. For example, try running the code without pass. Won't work. You can also try putting an unused expression (e.g. 0) or effect-less statement (e.g. print(end='')) in place of pass. But I would recommend removing these when possible. You could also set a conditional breakpoint instead of breaking within the if statement.

Update: As of Python 3.7+, one can now use the builtin breakpoint() function.

like image 80
Tyler Crompton Avatar answered Sep 26 '22 11:09

Tyler Crompton


Use Ellipsis!

For quick breakpoints or something that make minimum visual impact to you code, you may insert and break on an ... (Ellipsis):

For example:

while some_condition():
    do_something()
    ...  #  <<< set break point here!

this may the most clean way towards me.

Some background

Ellipsis is a special built-in python object mainly for Slice notating. Here I (ab)use it to do something else. See: What does the Python Ellipsis object do?

It is OK to insert a bare integer, variable name or something into code to set break point on certain place, but it may look odd and clutter your code, but ... is visually harmless. Compare with this:

break_point = 0
while some_condition():
    do_something()
    break_point # <<< set break point here!

or this:

while some_condition():
    do_something()
    if False: # <<< set break point here!
        pass

some other tricks tested:

del []  # works(with warning: "cannot assign to []")
[]  # works(with warning: Statement seems to have no effect)
setbreakpoint = 1  # works(with warning: "local variable value is not used")
Ellipsis  # works(with warning: Statement seems to have no effect)

another interesting thing that happens to me is, when i set breakpoints on pass it may or may not break, depending to its location in code, but the exact rule for break or not is somehow unclear.

like image 33
imkzh Avatar answered Sep 25 '22 11:09

imkzh