python - Avoiding the use of type() comparisons where polymorphism won't work -


i came across following in how think computer scientist (here):

def recursive_sum(nested_num_list):     sum = 0     element in nested_num_list:         if type(element) == type([]):             sum = sum + recursive_sum(element)         else:             sum = sum + element     return sum 

i shocked use of type(element) == type([]). not bad practice, function won't work other sequence types. polymorphism typical way of avoiding type comparisons, can't used here. how 1 avoid type comparison in such case? considered:

def recursive_sum(nested_sum_list):     sum = 0     element in nested_num_list:         try:             sum += element         except typeerror:             sum += recursive_sum(element)     return sum 

which makes function applicable other sequences, still kinda gross. thanks!

"sum" functions takes iterable, check element implements __iter__ method or not,using "hasattr" builtin function.

like this:

def recursive_sum(nested_num_list):     sum = 0     element in nested_num_list:         if hasattr(element, '__iter__'):             sum = sum + recursive_sum(element)         else:             sum = sum + element     return sum 

Comments