Is there a simple way to comment out or diable a python try statement without re-indenting

Viewed 227

Problem:
Sometimes it is nice to be able to remove or apply a try statement temporarily. Is there a convenient way to disable the try statement without re-indenting?

For example, if there was a python block statement equivalent called "goForIt:" one could edit the word "try:" to "goForIt:" and it would just execute the block as though it were not wrapped in a "try" and ignore the "except" line too.

The problem I'm trying to solve is that while I want the try statement in production I want to be able to remove it temporarily while debugging to see the error traceback rather than have it trap and process the exception.

Currently I work around this by commenting out the "try" then re-indent the code in the block. Then comment out the entire "except" block. This seems clumsy.

4 Answers

Instead of removing the try, you could make the except re-raise the exception:

try:
    raise ValueError('whoops')
except ValueError as e:
    raise # <-- just put this here
    print('caught')

This will raise the error, just as if it were not caught:

ValueError                                Traceback (most recent call last)
<ipython-input-146-a6be6779c161> in <module>
      1 try:
----> 2     raise ValueError('whoops')
      3 except ValueError as e:
      4     raise
      5     print('caught')

ValueError: whoops

I do not believe there is a way to fix this.

Is it adequate to catch the exception, print it out and, if wanted, end the program?

try:
  # code
except Exception as e:
  print(e)
  # end program if wanted

If you want a none code solution you need to use an IDE or a good text editor.
I am using Visual Studio code where I can indent with a keyboard shortcut (Ctrl + ` in my case)

(This is not my answer, but the answer from Alani's comment. If credits, find the original comment under the question.)

The solution is good because it allows global replacement:

try: --> if 1: # try:
except --> if 0: # except

The 2nd one is a little unsure. Exact and full word match should be used, or replace twice (for except<space> and except:). Or you can fix error fast by hand if there is any. The replacement back is sure.

I need now such solution to debug error in strawberry which is only printed. So I think I need deactivate all try/except structures in 3 libraries (strawberry + 2 libs for django).

Related