A DRY approach to Python try-except blocks

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

  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.

Answers

What about refactoring a function out of it?

def maybe_find_field(name, datum):
    try:
        return find_field(name, datum)[0]
    except IndexError: # Example of specific exception to catch
        return   

sample.thickness = maybe_find_field( Thickness , sample_datum)
sample.max_tension = maybe_find_field( Maximum Load , sample_datum)
sample.max_length = maybe_find_field( Maximum Extension , sample_datum)
sample.test_type = sample_test

BTW, don t simply catch all possible exceptions with except: unless that s really what you want to do. Catching everything may hide some implementation error that becomes quite difficult to debug later. Whenever you can, bound your except case to the specific exception that you need.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/38488476/a-dry-approach-to-python-try-except-blocks

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils