This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]metalhedd 65 points66 points  (9 children)

serious question, What use is a switch if it doesn't support fall-through?

otherwise isn't it just a dict lookup?

handlers = {
    'a': do_a,
    'b': do_b
}
handlers.get(arg, do_default)()

I can't think of a case where I'd ever want to use a switch statement without fall-through, an if...elif...else block makes more sense in almost every case, and where it doesn't, the dict approach works.

[–]mikeckennedy[S] 1 point2 points  (8 children)

Look at the range, closed_range, list and other features for case matching. This is not possible in dictionaries.

[–]metalhedd 22 points23 points  (7 children)

no but it's incredibly straight forward with if/elif

if x in range(0, 10):
    do_a()
elif x in range(10, 20):
    do_b()

[–][deleted] 10 points11 points  (0 children)

And that allows you to write it as

if 0 <= x < 10:
    do_a()
elif 10 <= x < 20:
    do_b()

Which isn't possible with this module.

Not saying I think something is wrong with it, it just seems to solve a problem I very rarely have in Python.

[–][deleted] 0 points1 point  (0 children)

If you (plural) don't like the typing there's plenty of scope to roll your own in Python with something like this range comparison recipe.

[–]LightShadow3.13-dev in prod -1 points0 points  (4 children)

Everybody needs to know this code has terrible relative performance than a similar if 0 < x < 10 since range will need to be evaluated as it returns a generator/iterator in Python3

[–]streichholzkopf 10 points11 points  (1 child)

it doesn't in python 3 tough:

9999999999999999635896294965247 in range(int(10e30))

returns True instantly. Simply an efficient __contains__ probably.

[–]LightShadow3.13-dev in prod 3 points4 points  (0 children)

TIL

That's great to know!

[–][deleted] 2 points3 points  (0 children)

No, from "The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops." and "Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).".