Rico
Rico

Reputation: 6042

Pythonic Solution to Multiple Checks

Suppose I have the following code:

var = foo()
if var:
    return var

var = bar()
if var:
    return var

var = baz()
if var:
    return var

Is there a more Pythonic approach to solve this problem? A good use case for something like this would be retrieving a user setting. If the user has a specific setting for a screen type then use it. If not, try to get the user's account-wide screen type and use it. If not, use a system-wide generic screen type.

Obviously this case is small and would probably be ok. Suppose I have over 100 "cases" to check in the priority list. I think we could all agree that could get ridiculous.

Edit: Sorry if this appears to be a XY question. In a way, it is I suppose. This is 100% an academic thought exercise. I don't actually have a specific use case for this. It's just something I was thinking about last night and was wondering what the most Pythonic approach would be.

Upvotes: 0

Views: 66

Answers (5)

Bahrom
Bahrom

Reputation: 4862

You could iterate over the functions and take the first one that returns a boolean True:

var = next(filter(None, (fn() for fn in (foo, bar, baz))))


Edit: this crashed for me when I tested it, and then I realized that in Python 2.x filter returns a list, whereas in Python 3.x filter returns a generator. For a Python 2.x example, see below:

def f1():
    print 'called f1'
    return False

def f2():
    print 'called f2'
    return None

def f3():
    print 'called f3'
    return 'yay'

def f4():
    print 'called f4'
    return 'yay1'

from itertools import ifilter

var = next(ifilter(None, (fn() for fn in (f1, f2, f3, f4))))
print var

This outputs:

called f1
called f2
called f3
yay
>>> 

Upvotes: 2

SpoonMeiser
SpoonMeiser

Reputation: 20417

If the number of functions could grow unbounded, I'd probably do something like:

functions = [
    foo,
    bar,
    baz
]

for fn in functions:
    var = fn()
    if var:
        return var

# some sort of error handling maybe?

Upvotes: 0

user5547025
user5547025

Reputation:

for f in [foo, bar, baz]:
    t = f()
    if t:
        return t

Upvotes: 0

user590028
user590028

Reputation: 11730

I think user161151's solution is good, but if you prefer to maintain dozens or even 100 functions, you could do something like this:

lst = [foo, bar, baz, ...]  # add to this list
for func in lst:
    v = func()
    if v:
        return v

Upvotes: 3

letmutx
letmutx

Reputation: 1416

return foo() or bar() or baz() should do it.

Upvotes: 4

Related Questions