3 ms·
I never understood the need for a switch, but one way to do it in python that is not mentioned in the article is to put different functions as the values of you
by dec0dedab0de 6y ago
I never understood the need for a switch, but one way to do it in python that is not mentioned in the article is to put different functions as the values of your dict. Then do my_dict[my_var]()
- sammorrowdrums 6y agoIndeed if you use a default dict, you could also emulate imtge pattern more completely. Happy for it not to have fall-through. I guess my_dict.get(myvar, default)() would be simple enough. That said, I never really had a problem not having switch either.
- path411 6y agoWhat would make you want it to explicitly not have fall-through? I can't see any negative to including it. If it's something you disagree with can't you just opt to not use? It's very useful in times for us who use switch regularly. I have no skin in the python game though so just curious from an outside dev haha
- sammorrowdrums 6y agoWell to be fair, I do use fallthrough in so far as I group cases that are the exact same, but fall-through with slightly different logic is very bug prone and difficult to spot when it is deliberate or an accident, so I basically never use it. Perhaps some languages conventions are different, but for example Douglas Crockford on JS: > "switch Statement A switch statement should be avoided, but when used should have this form: switch (expression) { case expression: statements default: statements } Each case is aligned with the switch. This avoids over-indentation. A case label is not a statement, and should not be indented like one. Each group of statements (except the default) should end with break, return, or throw. Do not fall through."
- path411 6y agoThat convention seems a little weird, but what works for different people. Normally case/break seem to light up in ides to help visually double check it has a break. Also not every language that supports fall through, supports having content inside the fall throughs. (C# I just learned recently, does not allow any code in a case that is falling through). My problem with languages trying to too strictly control stuff like this, is that this is stuff that should be handled in your code review process. Sometimes when working with old code, it's not really worth the time spent refactoring a whole switch when you need to make a small fix, vs adding a single line.
- karlding 6y agoYep, this pattern is known as Table-Driven Methods.
- jrimbault 6y agoThere's a pattern I have developed for my python scripts of writing a object like that : # where a and b are functions FOO = { a.__name__: a, b.__name__: b } and with argparse do parser = argparse.ArgumentParser() parser.add_argument( "-f", "--foo", choices=FOO.keys(), default=next(iter(FOO)), help="choose your type of foo", )
- anitil 6y agoI quite like that!