gsweene2 / garrett-learns-python

0 stars 0 forks source link

Does python have a switch statement? #1

Open dluftspring opened 3 years ago

dluftspring commented 3 years ago

Python can't be a real language because it doesn't have a switch or case statement

  • some C programmer probably

Python actually does have a nifty way of handling switch style statements using dictionaries.

>>> cases = {"case_1": do_something, "case_2": do_something_else, "case_3": stop_doing_the_thing}
>>> cases.get("case_1") #you can pass params from inside a class to your dictionaries to simulate switch statements

This brings up another important and nice feature of good python- using default values when looking up values in dictionaries

Say I want to check a bunch of values but have a common way of error handling without bugging out my whole program. A very good choice is to supply a default option when you lookup a value like so...

>>> some_dictionary = {'a':1,'b':2,'c':3,'ERROR':"Not in this alphabet my friend"}
>>> some_dictionary.get('a','ERROR')
1
>>> some_dictionary.get('xref','ERROR')
"Not in this alphabet my friend"

Another lesser known thing is that you can supply lambda functions as your default lookup value.

Python also has a collection in the standard library called a DefaultDict which is perfect for people who don't like supplying the default key every time they make a call to the underlying dictionary.

Happy snake charming...

gsweene2 commented 3 years ago

Python actually does have a nifty way of handling switch style statements using dictionaries.

Should I start replacing my Java switch statements with Maps? Perhaps an EnumMap

As far as defaults, I wonder what the underlying implementation looks like, vs using something like EnumMap's containsKey before getting the key from the map.

Regardless your Python will have much fewer lines with the built-in default, which is nice.

I will add an example of this in the Utilities class

dluftspring commented 3 years ago

Can't speak to Java but I can say that in python dictionary style switches will make your code more readable and definitely more performant than:

if case_1:

elif case_2:

elif case_3:

elif case_4:
.
.
.
elif case_N:

else:
"game over"
gsweene2 commented 3 years ago

Using dictonary get with default value: https://github.com/gsweene2/garrett-learns-python/commit/5533afb65037c98c10a82e744a7a7451ea780df8

I like the my_map.get(key, 'Not Found') I have been writing ternary like this instead my_map[key] if key in my_map else 'Not Found'

Ternary: https://github.com/gsweene2/garrett-learns-python/commit/8fbc1f1b8aac53476c0c548a9c0f267514a58ba7