Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
1
class TypeUtil:
2
3
@classmethod
4
def is_iterable(cls, obj):
5
"""Determines if obj is iterable.
6
7
Useful when writing functions that can accept multiple types of
8
input (list, tuple, ndarray, iterator). Pairs well with
9
convert_to_list.
10
"""
11
try:
12
iter(obj)
13
return True
14
except TypeError:
15
return False
16
17
@classmethod
18
def convert_to_list(cls, obj):
19
"""Converts obj to a list if it is not a list and it is iterable,
20
else returns the original obj.
21
"""
22
if not isinstance(obj, list) and cls.is_iterable(obj):
23
obj = list(obj)
24
return obj
25