[4suite] Generate empty strings instead of AttributeError

Eric Larson ionrock at gmail.com
Mon Mar 3 13:13:45 MST 2008


Hi,

On Mon, Mar 3, 2008 at 6:44 AM, Emil Stenström <em at kth.se> wrote:
> Hi,
>
>  I'm very new to Amara (and Python for that matter) and is using it the
>  simplest way possible, to parse an XML file from an external site. The
>  problem is that the file I'm parsing has a lot of optional elements, so
>  each element might or might not exist.
>
>  Since there's lots of optionality, I'm stuck catching AttributeErrors
>  all over the place, and I can't help hoping there's a better way to
>  handle this.
>
>  If list is the wrong forum for these kinds of beginner's questions: let
>  me know, and I'll look elsewhere.
>
>  ------
>  My python looks something like this:
>
>  books = {}
>  container = parse(url)
>  for element in container.elements:
>         books['name'] = element.name.author, " ", element.name.birthyear
>
>  Sample XML file (minified version, in the real one there's lots of
>  optional elements):
>
>  <elements>
>         <name>
>                 <author>Author 1</author>
>                 <birthyear>1982</birthyear>
>         </name>
>         <name>
>                 <author>Author 2</author>
>         </name>
>  </elements>
>  ------
>
>  Since two namePart entries only exists sometimes, I get attributeerrors
>  thrown. Is there a simple way to get around this?
>
>  Thanks in advance!
>
>  --
>  Emil Stenström
>  http://friendlybit.com

So, one way to handle this is to check if the attribute exists:

if hasattr(doc.some.node, 'some_attribute'):

This is a little better than the exception handling IMO, but I admit
it is a hair cumbersome. The other option is to use other means such
as XPath:

nodes = doc.xml_xpath(u'/some/node/@some_attribute')

Then the intention is clearer with a simple "if nodes". I think it was
being considered for Amara 2.0 to not throw an exception when you
request something that is not present, but in the mean time, the above
should help keep to make the processing a little simpler.

HTH,

Eric



>  _______________________________________________
>  4suite mailing list
>  4suite at lists.fourthought.com
>  http://lists.fourthought.com/mailman/listinfo/4suite
>


More information about the 4suite mailing list