Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I quickly disable a try statement in python for testing?

Say I have the following code:

try:
    print 'foo'
    # A lot more code...
    print 'bar'
except:
    pass

How would I for testing purposes disable the try-statement temporary?

You can't just comment the try and except lines out as the indention will still be off.

Isn't there any easier way than this?

#try:
print 'foo'
# A lot more code...
print 'bar'
#except:
#    pass
like image 492
Tyilo Avatar asked Dec 05 '12 23:12

Tyilo


People also ask

How do I stop a try block in Python?

In case that you are using an if statement inside a try , you are going to need more than one sys. exit() to actually exit the program. otherwise, you want to use one try-except block for each evaluation.

Is Try faster than if?

Python3. Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.


3 Answers

You could reraise the exception as the first line of your except block, which would behave just as it would without the try/except.

try:
    print 'foo'
    # A lot more code...
    print 'bar'
except:
    raise # was: pass
like image 122
Joseph Sheedy Avatar answered Oct 01 '22 02:10

Joseph Sheedy


Piggy-backing off of velotron's answer, I like the idea of doing something like this:

try:
    print 'foo'
    # A lot more code...
    print 'bar'
except:
    if settings.DEBUG:  # Use some boolean to represent dev state, such as DEBUG in Django
        raise           # Raise the error
    # Otherwise, handle and move on. 
    # Typically I want to log it rather than just pass.
    logger.exception("Something went wrong")
like image 16
alukach Avatar answered Oct 02 '22 02:10

alukach


Turn it into an if True statement, with the except clause 'commented out' by the else branch (which will never be executed):

if True: # try:
    # try suite statements
else: # except:
    # except suite statements

The else: is optional, you could also just comment out the whole except: suite, but by using else: you can leave the whole except: suite indented and uncommented.

So:

try:
    print 'foo'
    # A lot more code...
    print 'bar'
except SomeException as se:
    print 'Uhoh, got SomeException:', se.args[0]

becomes:

if True: # try:
    print 'foo'
    # A lot more code...
    print 'bar'
else: # except SomeException as se:
    print 'Uhoh, got SomeException:', se.args[0]
like image 5
Martijn Pieters Avatar answered Sep 29 '22 02:09

Martijn Pieters