简体   繁体   中英

What's the best way to handle nested try/catch AttributeError check?

Here's my code:

try:
    entry_date = entry.updated_date
except AttributeError:
    try:
        entry_date = entry.published_date
    except AttributeError:
        entry_date = manual_parse_from_string(entry)

In this scenario I'm parsing a feed and trying to get the date. RSS comes with updated_date , published_date or date in string format, which need further processing into the DateTime object. I have a feeling it can be done in an other way, such as in this pseudo-code:

entry_date = entry.updated_date
or
entry.published_date or manual_parse_from_string(entry)

None of those seems right to me. What would be the best way to do it?

In this particular case, you can use getattr with a None default value:

entry_date = (getattr(entry, 'updated_date', None)
              or getattr(entry, 'published_date', None)
              or manual_parse_from_string(entry))

Homogenise your different getters into uniform callables and iterate over them:

from operator import attrgetter

getters = attrgetter('updated_date'), attrgetter('published_date'), manual_parse_from_string

for getter in getters:
    try:
        entry_date = getter(entry)
    except AttibuteError:
        pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM