9. Use
(It's safer and more robust than
Cluttered Way (brittle, fails on subclasses):
Clean Way (correctly handles subclasses):
10. Use the
(Clearly separates the code that runs on success from the
Cluttered Way:
Clean Way:
#Python #CleanCode #Programming #BestPractices #CodeReadability
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
isinstance() for Type Checking(It's safer and more robust than
type() because it correctly handles inheritance.)Cluttered Way (brittle, fails on subclasses):
class MyList(list): pass
my_list_instance = MyList()
if type(my_list_instance) == list:
print("It's a list!") # This will not print
Clean Way (correctly handles subclasses):
class MyList(list): pass
my_list_instance = MyList()
if isinstance(my_list_instance, list):
print("It's an instance of list or its subclass!") # This prints
10. Use the
else Block in try/except(Clearly separates the code that runs on success from the
try block being monitored.)Cluttered Way:
try:
data = my_ risky_operation()
# It's not clear if this next part can also raise an error
process_data(data)
except ValueError:
handle_error()
Clean Way:
try:
data = my_risky_operation()
except ValueError:
handle_error()
else:
# This code only runs if the 'try' block succeeds with NO exception
process_data(data)
#Python #CleanCode #Programming #BestPractices #CodeReadability
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤10👍3