x=something, y=somethinelse and z=crud all likely to fail - how do i wrap them up

Chris Angelico rosuav at gmail.com
Sun Jan 31 00:23:18 EST 2016


On Sun, Jan 31, 2016 at 3:58 PM, Veek. M <vek.m1234 at gmail.com> wrote:
> I'm parsing html and i'm doing:
>
> x = root.find_class(...
> y = root.find_class(..
> z = root.find_class(..
>
> all 3 are likely to fail so typically i'd have to stick it in a try. This is
> a huge pain for obvious reasons.
>
> try:
>  ....
> except something:
>  x = 'default_1'
> (repeat 3 times)
>
> Is there some other nice way to wrap this stuff up?

I'm not sure what you're using to parse HTML here (there are several
libraries for doing that), but the first thing I'd look for is an
option to have it return a default if it doesn't find something - even
if that default has to be (say) None.

But failing that, you can always write your own wrapper:

def find_class(root, ...):
    try:
        return root.find_class(...)
    except something:
        return 'default_1'

Or have the default as a parameter, if it's different for the different ones.

ChrisA



More information about the Python-list mailing list