try — except if in Python

Most people don`t know that the Try-Except block can replace if-else (conditionals). Yes, you read that right! This can be done. We can use Try (Exception Handling) instead of regular conditional statements.

Here`s a very famous example:

Using If

 if key in mydict: mydict [key] + = 1 else: mydict [key] = 1 

Use try / except

 try: mydict [key] + = 1 except KeyError: mydict [key] = 1 

Sounds great! But then the question arises: which block of code is faster? 
This can be measured from the timeit module of the timeit in python. You can see whether the Try block should be used instead of the If
Example: time comparison for dividing 2 numbers using try-exc and if-else.

Below is the implementation.

import timeit

 

code_snippets = [ & quot; & quot; & quot; /

try:

result = 1000 / value

except ZeroDivisionError:

pass & quot; & quot; & quot; ,

& quot; & quot; & quot; /
if the value is:

result = 1000 / value & quot; & quot; & quot; ,

]

 

for value in ( 1 , 0 ):

  for code in code_snippets:

t = timeit. Timer (stmt = code, setup = `value = {}` . format (value))

print ( "----------------- ----- " )

  print ( "value = {} {}" . format (value, code))

print ( "%. 2f usec / pass" % ( 1000000 * t.timeit (number = 100000 ) / 100000 ))

Exit:

 --- --------- ---------- value = 1 try: result = 1000 / value except ZeroDivisionError: pass 0.04 usec / pass ---------------------- value = 1 if value: result = 1000 / value 0.06 usec / pass ---------------------- value = 0 try: result = 1000 / value except ZeroDivisionError: pass 0.37 usec / pass ---------------------- value = 0 if value: result = 1000 / value 0.01 usec / pass 

Now you can clearly see that an exception handler (try / exception) is comparatively faster than an explicit if condition until it encounters an exception. This means that if any exception is thrown, the exception handler took longer than it would if the code version. This means that the factor that decides code speed is the type of problem being solved.

We often hear that python always encourages ESPC (“It`s easier to ask forgiveness than permission”) style more LBYL (“Look before you jump”) style used in most languages ​​such as C. Python DOCS states which —

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages ​​such as C.

From our assessment, we come to the following conclusion. Let`s take a look at the above example. If we expect 99% of the time the values ​​& # 39; value & # 39; will not be 0, we can use a try / exception approach. It will be faster if the exception is truly exceptional. If there is more than 50% chance of the value going to 0, then it is better to use “if”.