Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing method call as a variable to error handling function

Trying to implement simple error handling without adding buku try / except statements to my code.

My if_error function tries to emulate the iferror(value,value_if_error) formula in excel.

If the value (another formula) is valid, 
     return its resulting value 
else 
     return value_if_error

How can I pass a method call from a beautifulsoup object (soup) with parameters to a generic try/ except function?

  • Tried lambda but didn't understand enough to make it work with parameters & soup.
  • Looked at Partial but didn't see how that would call the beautiful soup method
  • Looked at this but didn't see how soup would be passed?

My Code:

def if_error(fn,fail_value):
    try:
      value = fn
    except:
      value = fail_value
    return value

def get_trulia_data(soup):
    d = dict()

    description = if_error(soup.find('div', attrs={'class': 'listing_description_module description'}).text,'')

    sale_price = if_error(soup.find('div', attrs={'class': 'price'}).text,'0')
    sale_price = re.sub('[^0-9]', '', sale_price)

    details = if_error(soup.find('ul', attrs={'class': 'listing_info clearfix'}),'')

    bed = if_error(soup.find('input', attrs={'id': 'property_detail_beds_org'})['value'],'')
    bath = if_error(soup.find('input', attrs={'id': 'property_detail_baths_org'})['value'],'')

    ...

    return d

Error:

Traceback (most recent call last):
data_dict = get_trulia_data(url)
description = if_error(soup.find('div', attrs={'class': 'listing_description_module description'}).text,'')
AttributeError: 'NoneType' object has no attribute 'text'

The soup.find method keeps firing before the if_error function is reached. How can I fix this?

like image 551
mitrebox Avatar asked Aug 05 '26 16:08

mitrebox


1 Answers

How about this:

def if_error(fn, fail_value, *args, **kwargs):
    try:
      return fn(*args, **kwargs)
    except:
        return fail_value

def test_fail(x):
    raise ValueError(x)

def test_pass(x):
    return x

if __name__=='__main__':
    print if_error(test_fail, 0, 4)
    print if_error(test_pass, 0, 5)
like image 162
Meitham Avatar answered Aug 07 '26 06:08

Meitham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!