Which of these two functions is more pythonic?

I just want to know which path is preferable in python. Imagine two functions:

1 function:

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 

2:

 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 the else . So the question is whether it will affect performance. Or are there any reasons to include else in this type of function?

+6
source share
3 answers

If the choice is between these two approaches, I would choose the first. return pretty clear that execution ends at this point. For this reason, I find if x { return y } else { ... } anti-pattern (not only in Python - I see this in C / C ++ code, and this is also annoying).

If you return, the else block is completely unnecessary and causes a meaningless indentation of the code block, which can be quite large. The more nested structures you have, the more difficult it is to maintain the right context in your head when reading code. For this reason, I prefer less nesting when it does not confuse logic, in which case I do not think it would be.

+7
source

The pythonic way:

 def foo(key): return bar.get(key, something) 
+4
source

Although this question is based on a small number of opinions, I would say that the second is more Pythonic because "explicit is better than implicit." The second function clearly says: โ€œIf this is a condition, do it. Otherwise, do it.โ€ On the other hand, the first function implies the โ€œOtherwiseโ€ part.

+4
source

Source: https://habr.com/ru/post/952759/


All Articles