7
\$\begingroup\$

This is a very subjective question, but I'm curious as to other people's opinions.

Would you find this bit of code distasteful? Is it cryptic and unreadable, or is it using features of the language in an elegant way?

def winning_side(home_goals, away_goals):
    """Takes a home score and an away score, and returns the winner

    Return DRAW, HOME or AWAY depending on the outcome
    """
    return (DRAW, HOME, AWAY)[cmp(home_goals, away_goals)]

The alternative obviously being explicit if-else statements:

def winning_side(home_goals, away_goals):
    """Takes a home score and an away score, and returns the winner

    Return DRAW, HOME or AWAY depending on the outcome
    """
    if home_goals > away_goals:
        return HOME
    elif away_goals > home_goals:
        return AWAY
    else:
        return DRAW

I personally find the verbose if-else logic in the latter solution, and the assumed equality in the 3rd branch, less appealing.

\$\endgroup\$
2
  • \$\begingroup\$ Even without ferada's accurate note that this is implementation-dependent: yes, that is incredibly cryptic. Beautiful code is not code which uses the most tricks, it's code which is the most easily understood at first glance. Looking at your first implementation, I have to think hard about at least three different things to determine what the result will be, especially if I don't frequently use Python. \$\endgroup\$ Commented Feb 12, 2015 at 3:56
  • \$\begingroup\$ Isn't one of the tenets of Python something along the lines of: "Be simple/clear instead of clever". In terms of team development, I would say using cmp falls to the clever category. \$\endgroup\$ Commented Feb 12, 2015 at 7:59

1 Answer 1

11
\$\begingroup\$

The documentation to cmp says nothing about the return value except it being negative, zero or positive, so you rely on implementation-dependent behaviour. This exact function will also not work in Python 3, as there is no cmp function anymore.

I'd say use the second option or shorten it a bit:

def winning_side(home_goals, away_goals):
    if home_goals == away_goals:
        return DRAW

    return HOME if home_goals > away_goals else AWAY
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You make some very good points! Never a good idea to rely on implementation specific behaviour.. \$\endgroup\$
    – Acorn
    Commented Feb 11, 2015 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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