Rico Rico - 2 years ago 87
Python Question

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.

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download