Question

Many a times I have a situation where individual statements like below can throw an exception which I dont care about , in the case of exception it should just return an empty string:

name="".join(b.find(itemprop='name').contents)
phone= "".join(b.find(itemprop='telephone').contents)
fax="".join(b.find(itemprop='faxNumber').contents)

instead of running all statements , if the first statement causes exception than the whole execution is stopped, eg:

AttributeError: 'NoneType' object has no attribute 'contents'

So without using try catch finally for such long list of statements , how can I ensure that I just run all the statements as above forcefully? there are many dozens of sequential statements to run hence dont want to use try catch construct.

Was it helpful?

Solution

An alternative similar to @jbaiter's solution is to use a local function. This avoids having to pass an extra argument, producing slightly more readable code.

You can also avoid the use of exceptions in the first place:

def find_field(name):
    x= b.find(itemprop=name)
    return "".join(x.contents) if hasattr(x,'contents') else ""

name, phone, fax = map(find_field, ['name','phone','fax'])

OTHER TIPS

Try to abstract the individual statements into a single function and put the try...catch inside of it:

def find_field(name, b):
    try:
        return "".join(b.find(itemprop=name).contents)
    except AttributeError:
        return ""

name = find_field('name', b)
phone = find_field('phone', b)
fax = find_field('fax', b)

An alternative method is to use getattr:

name = "".join(getattr(b.find(itemprop="name"), "contents", ""))

The default argument to getattr ("", in this case) is returned if the object (b.find(...)) doesn't have an attribute name ("contents").

You can still reduce the duplication by making this a function:

def find_field(item, prop):
    return "".join(getattr(item.find(itemprop=prop), "contents", ""))


name = find_field(b, 'name')

As Jon Clements points out, one benefit of getattr over try/except is that if b.find(...) raises an AttributeError (i.e. b isn't what you think it is, likely a genuine error), the error will still be thrown. You could adapt this into try/except using:

item = b.find(itemprop="name")
try:
    name = "".join(item.contents)
except AttributeError:
    name = ""
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top