how to test attribute existence of feedparser objects

Discussion in 'Python' started by HansPeter, Dec 8, 2011.

  1. HansPeter

    HansPeter Guest

    Hi,

    While using the feedparser library for downloading RSS feeds some of
    the blog entries seem to have no title.

    File "build\bdist.win32\egg\feedparser.py", line 382, in __getattr__
    AttributeError: object has no attribute 'title'

    Is there a way to test the existence of an attribute?

    I can use an exception but like below to see whether it exists but
    this is a clumsy way since the function has to return the title.

    d=feedparser.parse(url,handlers = [proxy])
    try:
    print "TITLE ",d.feed.title
    except:
    print "HAS NO TITLE"
    wc={}

    Regards HansPeter
     
    HansPeter, Dec 8, 2011
    #1
    1. Advertisements

  2. HansPeter

    Chris Rebert Guest

    hasattr(obj, attr_name)
    See docs.python.org/dev/library/functions.html#hasattr

    That said, sounds like it won't make much difference in the particular
    case you mention.
    Also, never use a bare "except:" clause, unless you know what you're
    doing and have a really good reason. Do "except AttributeError" in
    this case.

    Cheers,
    Chris
     
    Chris Rebert, Dec 8, 2011
    #2
    1. Advertisements

  3. HansPeter

    xDog Walker Guest

    From the Fine Manual for feedparser 5.1:

    Testing for Existence¶

    Feeds in the real world may be missing elements, even elements that are
    required by the specification. You should always test for the existence of an
    element before getting its value. Never assume an element is present.

    Use standard Python dictionary functions such as has_key to test whether an
    element exists.
    Testing if elements are present¶
    60
     
    xDog Walker, Dec 10, 2011
    #3
  4. Idiomatic Python code today no longer uses has_key.

    # Was:
    d.feed.has_key('title')

    # Now preferred
    'title' in d.feed
     
    Steven D'Aprano, Dec 10, 2011
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.