Search code examples
pythonexceptiondefault-valuenonetype

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.


Solution

  • 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