[Python-ideas] Another indentation style

Andrew Barnert abarnert at yahoo.com
Sun Sep 1 15:21:39 CEST 2013

On Sep 1, 2013, at 4:10, Rob Cliffe <rob.cliffe at btinternet.com> wrote:

> def test(condition, a, b):
>     if condition=='equals'          : return a==b
>     if condition=='is greater than' : return a>b
>     if condition=='contains'        : return b in a
>     if condition=='starts with'     : return a.startswith(b)

This isn't _terrible_... But it argues against the original proposal even further, because it's an example of a one-line if statement that's explicitly set off in a way that's unmistakable, because the statements can't be continued.

That being said, I think it would be much better to write:

_ops = {
    'equals': eq,
    'is greater than': gt,

def test(condition, a, b):
    return _ops[condition](a, b)

... Or maybe the equivalent with methods instead of functions from operator. Or, if some of the conditions don't already have functions with nice names to map to (e.g. "within 1%" mapping to .99*b <= a <= 1.01*b) maybe even inline lambdas.  

Besides reducing all the boilerplate repetition, having the mapping in data instead of code gives you the flexibility to do all kinds of things that would otherwise be impossible--register new conditions dynamically, inspect the conditions, reuse them in another function without a parallel chain of if statements, etc.

More information about the Python-ideas mailing list