r/pythontips • • Jun 03 '16

Syntax Replace chained conditionals with dict

Python has no case statement, and it sometimes leads to long ugly lists of conditionals, like so:

if myvar == 'a':
    do_a()
elif myvar == 'b':
    do_b()
elif myvar == 'c':
    do_c()

Instead of long lists of conditionals, you can build a simple dictionary of the options and outputs and just pass the parameter you're switching on into the dictionary:

output_dict = {'a': do_a,
               'b': do_b,
               'c': do_c}
output_dict[myvar]()

If you need an else, statement, instead of this:

    if myvar == 'a':
        do_a()
    elif myvar == 'b':
        do_b()
    elif myvar == 'c':
        do_c()
    else:
        do_else()

you can pass your default into a getattr call, like this:

output_dict = {'a': do_a,
               'b': do_b,
               'c': do_c}
output_dict.get(myvar, do_else)()

Easier to read, more pythonic

27 Upvotes

31 comments sorted by

3

u/cismalescumlord Jun 03 '16

Neat but can it handle

if myvar == 'a':
    do_a(p1, p2)
elif myvar == 'b':
    do_b(p1)
else:
    do_else()

4

u/nnutter Jun 04 '16 edited Jun 04 '16

How about,

output_dict = {'a': lambda: do_a(p1, p2),
               'b': lambda: do_b(p1)}
output_dict.get(myvar, do_else)()

repl.it

1

u/bad_luck_charm Jun 04 '16

That works, too. I try to avoid using lambdas in any but the simplest of use cases because I think they're hard to read, but this case is pretty straightforward.

2

u/bad_luck_charm Jun 03 '16 edited Jun 03 '16
output_dict = {'a': do_a,
               'b': do_b,
               'c': do_c}
output_dict.get(myvar, do_else)(p1, p2)

As long as all of your methods can optionally take in those parameters, sure. Otherwise, you can start adding more elements to the dictionary and passing in args and kwargs based on where you hit the dictionary (or better yet, take in different kwarg sets in the methods.) I've gotta run, but lemme know if you want to see that written out.

2

u/basalamader Jun 03 '16

Wait so how does the interpreter identify which variable you are looking to pass? Like how does it know that do_b(p1) takes in only p1 and not p1and p2

2

u/bad_luck_charm Jun 03 '16

There are two ways:

  1. Have do_a and do_b both defined as do_x(p1=None, p2=None) and handle the null values.

  2. construct the dict with additional information:

     output_dict = {'a': {'method': do_a, 'values': (p1, p2)},
                    'b': {'method': do_b, 'values': (p1,)}}
     output_dict[myvar]['method'](*output_dict[myvar]['values'])

Presuming that the methods are pretty similar (or else why are you doing this?) I would prefer the first one, but the second one is totally viable.

1

u/cismalescumlord Jun 03 '16

Found a third way ;) See above

1

u/bad_luck_charm Jun 03 '16

Sure, that's the same idea as #1: modifying the methods to accept all of the arguments.

1

u/cismalescumlord Jun 04 '16 edited Jun 04 '16

But it's prettier, at least to my eye.

Seriously, you don't have to define functions with named and defaulted parameters that are not needed, meaningless and maybe even confusing in the context. Depending on the complexity of the use case it may be worth adding a bit of syntactic sugar to the functions and parsing args to well named locals.

1

u/cismalescumlord Jun 03 '16

I think I' get it, but I'm going to have to experiment a bit.

1

u/bad_luck_charm Jun 03 '16

it may make it more obvious if I write it:

myfunc = output_dict[myvar]
myfunc(p1,p2)    

1

u/cismalescumlord Jun 03 '16 edited Jun 03 '16

OK, so this works fine

def fa (*args):
    print("fa")
    print(args[0])

def fb (*args):
    print("fb")
    print(args[0], ' ', args[1])

def fe(*args):
    print("fe")
    print()

d = {'a': fa, 'b': fb}

p1 = "Hello"
p2 = "World"
v = 'b'

d[v](p1, p2)

it turns out that getattr doesn't work with dictionaries but there is a way to do the same thing:

d.get(v, fe)(p1, p2)

3

u/rochacbruno Jun 03 '16

Why this

getattr(output_dict, myvar, do_else)()

instead of this

output_dict.get(myvar, do_else)()

2

u/bad_luck_charm Jun 03 '16 edited Jun 03 '16

I sometimes forget where .get works and where it doesn't. Updated the code.

2

u/Boolderdash Jun 04 '16

You don't even need to store the dictionary in a variable, as far as I'm aware. You can just do

{'a': do_a,
 'b': do_b,
 'c': do_c}[myvar]()

Although I'm sure there are arguments for and against doing it this way. I just don't like declaring a variable to only use it immediately on the next line and nowhere else.

1

u/bad_luck_charm Jun 04 '16

True, but I think this is messier.

0

u/Cybersoaker Jun 03 '16

I would argue that this is less pythonic; remember from the zen of python, explicit is better than implicit. This does not explicitly show that it's doing conditionals; almost every programmer would expect there to be if's, else's, etc.

However it is a neat little trick that could be applied to other things.

2

u/bad_luck_charm Jun 03 '16

beautiful is better than ugly

flat is better than nested

readability counts

I also don't think there's anything about it that's not explicit. It's just a different structure.

2

u/Cybersoaker Jun 04 '16

An explicit if statement would have an if in it; that is what explicit means. And doing if elif's isn't nested; nesting would be an if in an if in an if, etc. Again it's not really readable if you dont understand that methods are first class objects in python; and even then; you have to catch the subtle line that actually calls a method.

Using callbacks can be powerful but shouldn't be a makeshift switch case statement.

1

u/bad_luck_charm Jun 04 '16

It's not difficult to make it more explicit by assigning the function before calling it. I think this structure is much nicer than an endless chain of if statements. Keeps the code succinct and dry.

2

u/[deleted] Jun 04 '16

Again it's not really readable if you dont understand that methods are first class objects in python

Yes, and the alternative is not really readable if you don't understand if-elif-else. Nothing is readable if you don't understand the basic features of the language

You're look at the problem as an "if" and based on the assumption that "if" is the explicit way to describe this code claiming that "if" is more explicit. If you look at it as choosing which of a number of methods to execute based on the value of a variable, then the dict way looks more explicit.

1

u/Cybersoaker Jun 04 '16

True but the title of this post; 'replacing conditionals with a dict'

There's nothing wrong with doing callback style programming; all i'm saying is that it is much easier to understand at a glance that you're doing conditional statements rather than a callback lookup from a dict. Especially for newcomers to your project or newcomers to python; they will likely be confused by this.

If you get to the point where u need to do like 30 comparisons; that might be a sign that you need to reconsider how you've structured your code. This also forces you to make a function for each conditional; and you would have to consider how to abstract out arguments needed to go to those; AND god forbid you have to do a slightly more complex if statement in one of them like if myVar and myOtherVar

2

u/[deleted] Jun 04 '16

I'm not sure why you keep saying "callback", I think you're a little confused about terminology. Not all instances of using first-class functions are "callback style programming".

I also reject that we should write code aimed at being clear to newcomers to python. We should use features that make the code clearer.

There are going to be situations where the if-else pattern is better and others where the dict pattern makes sense.

0

u/Cybersoaker Jun 04 '16

Passing a function pointer around is what a callback is / does. Call it whatever you like; but the correct computer science term for it is callback.

And I didn't say we have to aim all our code at python newcomers; but when we are using language features to unnecessarily abstract a concept that is fundamental to almost all programming languages; then many folks looking to contribute to your code will be confused.

It is unlikely that you will go your entire career either not reading or sharing code; or working on a team with various degrees of python knowledge.

2

u/[deleted] Jun 04 '16

Passing a function pointer as an argument to a function is one way to implement callbacks. This is not how callbacks are done in Java 7, for example.

You are confusing callbacks and first-class functions.

1

u/Cybersoaker Jun 04 '16

https://en.wikipedia.org/wiki/Callback_(computer_programming)

"Programming languages support callbacks in different ways, often implementing them with subroutines, lambda expressions, blocks, or function pointers."

Doing what OP suggests is indeed callback-style programming; it doesnt have to be asynchronous to be a callback. Also arguing over what its called is frivolous...

1

u/[deleted] Jun 04 '16

Callback (computer programming)


In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback. In all cases, the intention is to specify a function or subroutine as an entity that is, depending on the language, more or less similar to a variable.

Programming languages support callbacks in different ways, often implementing them with subroutines, lambda expressions, blocks, or function pointers.


I am a bot. Please contact /u/GregMartinez with any questions or feedback.

1

u/[deleted] Jun 04 '16

"In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time."

It need not be asynchronous, but there is a notion of "calling back" "at some convenient time". Take a function like map. Does it really make sense to say that it takes a callback and calls it back on every element of the list? Why not say that it's a higher order function that applies a function argument to every element in the list?

What about this Haskell function signature: fmap :: Functor f => (a -> b) -> f a -> f b

If you refer to the first argument as a "callback", all you are doing is setting up to confuse yourself and anyone you talk to.

I suspect you're purposefully using less clear terminology just because it allows you to be pedantic about it.

→ More replies (0)

1

u/emigul Jun 05 '16

At the same time, can't you argue that because the right tool for what you are trying to achieve is a case statement (since all you are doing equality checks, not something that definitively requires an if check), that if statements aren't actually necessary here (explicit or implicit)?

I'm not an expert on how the Python compiler works, but I would expect OP's method to also be more performant and also easier to maintain. This method seems to be making use of some pretty basic Python concepts. I think you'd have trouble with other people's Python code anyway if you don't understand that functions are first class objects.

1

u/Cybersoaker Jun 05 '16

From a performance standpoint; comparing a single variable against a bunch of values is likely faster than doing dictionary lookups. Yes Python dicts are indeed fast compared to other data structures; but that comparison variable will likely remain in L1 CPU cache and dicts simply cannot do that to my knowledge.

That being said; i have no idea which would be faster without actually testing that. They both complete in O(1) so the performance difference is likely a moot point.

Also; Guido himself has rejected the switch case on numerous occasions. The right tool for doing comparisons is the if elif else statements. Is there a valid use case for this kind of thing? Absolutely; but it is not and should not be a replacement for comparison operators.

I'd be fine; I wouldn't like this but I could understand it. But what about the new hire on your team who only knows Java? What about the poor sys admin who has to dig through your code when it breaks in prod? Using advanced language features to unnecessarily abstract a concept is only hurting your code base when the alternative is the almost universal language construct of comparison operators.

It is also okay to declare classes by generating a dict that has the same members as a class object? You're able to do that; but we have a syntax for explicitly declaring classes already and you're only hurting your codes ability to be understood.

Do this in your own stuff; fine, who cares. Do this at a job, and it likely wouldn't make it through code review. And if it does; guess who is going to be answering "what does this do" question constantly.