-3
\$\begingroup\$

I often write statements such as:

def foo():
   if condition:
       return True
   else:
       return False

To me, it makes sense to just drop the else, giving the cleaner:

def foo():
   if condition:
       return True
   return False

This is a trivial example which could be rewritten as a ternary operator:

def foo():
    return True if condition else False

but, for more extended logic, is this a good idea? What about for longer chains containing elifs? (I normally use a dictionary there, though).

Which of these would you consider "best"?

1:

def foo(condition):
    if condition == condition_one:
        return 1
    elif condition == condition_two:
        return 2
    elif condition == condition_three:
        return 3
    else:
        return 4

2:

def foo(condition):
    if condition == condition_one:
        return 1
    elif condition == condition_two:
        return 2
    elif condition == condition_three:
        return 3
    return 4

3:

def foo(condition):
    conditions = {condition_one: 1, condition_two: 2, condition_three: 3}
    return conditions.get(condition, 4)

Finally, are there any speed considerations? How does that scale with the number of conditions?

Thanks.

\$\endgroup\$

closed as off-topic by πάντα ῥεῖ, Mathias Ettinger, Ludisposed, Graipher, AJNeufeld Feb 10 at 16:31

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Mathias Ettinger, Ludisposed, Graipher, AJNeufeld
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ For the first one, why not return bool(condition) (assuming condition isn't already a boolean, in which case return condition would suffice)? \$\endgroup\$ – mistertribs Feb 10 at 11:45
-1
\$\begingroup\$

This is a bit more of a Stack Overflow question.

There isn't really any reason to choose one over the other (personally I prefer your switch dictionary). Some style guides say not to put an else statement in when your if/elifs all have a return statement - so I think the pythonic version is 2.

There is a fourth way: use polymorphism to define either condition.foo() or object.foo(). Since you haven't posted a serious use-case, I can't determine whether it would be appropriate in your setting.

Adding switch/case to python was rejected, so that isn't an option.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.