Last active
April 16, 2018 06:19
-
-
Save nickangtc/a462c1d8db45e2e8ff54fb3744833ff3 to your computer and use it in GitHub Desktop.
For discussing the best approach for handling type errors in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def increment_list_by(list, num): | |
'''Increment all items in a list by `num` | |
provided all items are `int` types. | |
Return modified list if successful, or original list otherwise.''' | |
incremented_list = [] | |
# ============= | |
# Note: below are 2 separate approaches to implement this function | |
# ============= | |
# Approach 1: handle type error with conditional | |
for idx, item in enumerate(list): | |
if not (type(item) is int or type(item) is float): | |
print('Cannot increment list with non-integer values, returning as-is') | |
return list | |
incremented_list.append(list[idx] + 1) | |
return incremented_list | |
# Approach 2: handle type error with try-except | |
for idx, item in enumerate(list): | |
try: | |
incremented_list.append(list[idx] + 1) | |
except TypeError: | |
print('Cannot increment list with non-integer values, returning as-is') | |
return list | |
return incremented_list | |
# TEST (same result for both implementations) | |
print(increment_list_by([1, 3, 99, 3, 2, 9.9], 1)) | |
#=> [2, 4, 100, 5, 5, 5, 4, 3, 10.9] | |
print(increment_list_by([1, 3, 99, 3, '2', 9.9], 1)) # note '2' instead of 2 | |
#=> Cannot increment list with non-integer values, returning as-is | |
# [1, 3, 99, 4, 4, 4, 3, '2', 9.9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After discussing with some friends, I'd pick approach #2 in this case.
See this relevant discussion on Stackoverflow for how to think about choosing one or the other (it's not a hard rule): https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain