Using Exceptions instead of Dynamic Typing
Posted on Mon 17 May 2021 in Better Python
Python's dynamic typing is great, right? You can just do whatever you want with variables. FREEDOM! ;-) This comes at a price though, and sometimes one we're not always aware of.
Trying not to fail
For years I took advantage of Python's dynamic typing by having functions return an error state via a different data type. For example:
def double(int_input):
if not isinstance(int_input, int):
return "An integer must be provided"
return int_input * 2
And consuming this function would have looked like this:
doubled_int = double(user_input)
if isinstance(doubled_int, str):
print("You did not provide an integer")
return
print(f …
Continue reading