views:

329

answers:

1

I am using BeautifulSoup to parse XML:

xml = """<person>
<first_name>Matt</first_name>
</person>"""

soup = BeautifulStoneSoup(xml)
first_name = soup.find('first_name').string
last_name = soup.find('last_name').string

But I have a problem when there is no last_name, because it chokes. Sometimes the feed has it, and sometimes it doesn't. How do I prevent it from choking?

I don't want to use try/except statements. I also do not want to use if/else statements. (Since it'll double the lines of the already-very-long code if I have those statements).

Is there any way to just return "None" if there is no "last_name"?

+3  A: 
last_name = soup.find('last_name') and soup.find('last_name').string

Very silly, but it does meet your equally silly stated restriction (no if). A bit less silly:

last_name_node = soup.find('last_name')
last_name = last_name_node and last_name_node.string

and:

last_name = getattr(soup.find('last_name'), 'string', None)

These two don't have the same overhead as the first. I think a simple if is more readable than any of these, though.

Alex Martelli
I prefer the getattr version of your answer because I believe that's exactly what getattr was created in the first place!
Mike Sherov
Readable, but would double the lines :) thanks again alex :)
TIMEX
@alex: Oh, no! My source code files have lots of linefeed characters in them. Whatever will I do?
Roger Pate
@alex: Perhaps you might like to explain (by editing your question) with an example what you mean by "double the lines" and how this would happen with Alex Martelli's `getattr` suggestion. Using the default arg of `getattr` (or the `get` method of dicts and Elementtree elements) is the usual way of avoiding an `if` or `try` in a readable-enough manner.
John Machin
@John, I think @alex is referring only to my suggestion that `if` can be more readable!
Alex Martelli