Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Pythonic way to use a default value when function returns None or throws exception?

What's a more pythonic way of doing this?

try:
    a = foo() or b
except AttributeError:
    a = b

I want to set a to be the return of the function foo, but if foo returns None or an AttributeError exception is raised, then I want a to be set to b.

like image 991
Adrian Avatar asked Dec 21 '25 15:12

Adrian


1 Answers

as pointed out by Gennady Kandaurov: you'd need to test for 'valid' return values of foo() that are not 'truthy' (as 0, [], (), ...):

try:
    a = foo() if foo() is not None else b
except AttributeError:
    a = b

depending on the implementation details of foo (whether it is expensive or has side-effects) you may want to call it once only:

try:
    f = foo()
    a = f if f is not None else b
except AttributeError:
    a = b
like image 159
hiro protagonist Avatar answered Dec 23 '25 05:12

hiro protagonist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!