I just want to know which way is more preferable in python. Imagine two functions:
def foo(key):
if bar.has_key(key):
return bar.get(key)
# do something with bar
# this will be executed if bar_key(key) is False
...
return something
def foo(key):
if bar.has_key(key):
return bar.get(key)
else:
# do something with bar
# this will be executed if bar_key(key) is False
...
return something
As you can see the only difference is else
statement. So the question is will it affect performance somehow. Or are there any reasons to include else
in this type of functions?
The pythonic way:
def foo(key):
return bar.get(key, something)
If the choice is between those two approaches, I would pick the first one. return
is pretty explicit that execution terminates at that point. I find if x { return y } else { ... }
an anti-pattern for this reason (not just in Python -- I see this in C/C++ code and it irks me there, too).
If you are returning, an else
block is entirely unnecessary and causes pointless indentation of a block of code that might be quite large. The more nested structures you have, the more difficult it is to maintain proper context in your head while reading code. For this reason I tend to prefer less nesting when it does not obfuscate logic, and in this case I don't think it would.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With