Open dluftspring opened 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
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"
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
Python actually does have a nifty way of handling switch style statements using dictionaries.
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...
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...