2015-01-24 05:47:51 +08:00
|
|
|
class Util:
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def is_iterable(self, obj):
|
2015-01-24 20:08:07 +08:00
|
|
|
"""Determines if obj is iterable.
|
|
|
|
|
|
|
|
Useful when writing functions that can accept multiple types of
|
|
|
|
input (list, tuple, ndarray, iterator). Pairs well with
|
|
|
|
convert_to_list.
|
|
|
|
"""
|
2015-01-24 05:47:51 +08:00
|
|
|
try:
|
|
|
|
iter(obj)
|
|
|
|
return True
|
|
|
|
except TypeError:
|
|
|
|
return False
|
2015-01-24 05:58:34 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def convert_to_list(self, obj):
|
2015-01-24 20:08:07 +08:00
|
|
|
"""Converts obj to a list if it is not a list and it is iterable, else
|
|
|
|
returns the original obj.
|
2015-01-24 05:58:34 +08:00
|
|
|
"""
|
|
|
|
if not isinstance(obj, list) and self.is_iterable(obj):
|
|
|
|
obj = list(obj)
|
|
|
|
return obj
|