Objective: I have several lines of code each capable of producing the same type of error, and warranting the same kind of response. How do I prevent a do not repeat yourself problem with the try-except blocks.
Background:
I using ReGex to scrape poorly formatted data from a text file, and input it into the field of a custom object. The code works great except when the field has been left blank in which case it throws an error.
I handle this error in a try-except block. If error, insert a blank into the field of the object (i.e. ).
The problem is it turns easily readable, nice, Python code into a mess of try-except blocks that each do exact same thing. This is a do not repeat yourself (a.k.a. DRY) violation.
The Code:
Before:
sample.thickness = find_field( Thickness , sample_datum)[0] sample.max_tension = find_field( Maximum Load , sample_datum)[0] sample.max_length = find_field( Maximum Extension , sample_datum)[0] sample.test_type = sample_test
After:
try: sample.thickness = find_field( Thickness , sample_datum)[0] except: sample.thickness = try: sample.max_tension = find_field( Maximum Load , sample_datum)[0] except: sample.max_tension = try: sample.max_length = find_field( Maximum Extension , sample_datum)[0] except: sample.max_length = try: sample.test_type = sample_test except: sample.test_type =
What I Need:
Is there some Pythonic way to write this? Some block where I can say if there is an index-out-of-range error on any of these lines (indicating the field was blank, and ReGex failed to return anything) insert a blank in the sample field.