Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of these two functions more "pythonic"? [closed]

Tags:

python

I just want to know which way is more 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 function:

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?

like image 747
Vor Avatar asked Aug 29 '13 17:08

Vor


2 Answers

The pythonic way:

def foo(key):
    return bar.get(key, something)
like image 26
Matt Bryant Avatar answered Nov 02 '22 00:11

Matt Bryant


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.

like image 66
cdhowie Avatar answered Nov 02 '22 01:11

cdhowie