Added snippet to convert an object to a list. Useful when writing functions that can accept multiple types of

input (list, tuple, ndarray, iterator).
This commit is contained in:
Donne Martin 2015-01-23 16:58:34 -05:00
parent 52552208c1
commit 4c94ff5948
2 changed files with 14 additions and 0 deletions

View File

@ -39,3 +39,7 @@ class TestUtil():
def test_is_iterable(self):
assert_equal(Util.is_iterable('foo'), True)
assert_equal(Util.is_iterable(7), False)
def test_convert_to_list(obj):
assert_equal(isinstance(Util.convert_to_list('foo'), list), True)
assert_equal(isinstance(Util.convert_to_list(7), list), False)

10
util.py
View File

@ -7,3 +7,13 @@ class Util:
return True
except TypeError:
return False
@classmethod
def convert_to_list(self, obj):
"""Useful when writing functions that can accept multiple types of
input (list, tuple, ndarray, iterator). Checks if the object is a list.
If it is not a list, converts it to a list.
"""
if not isinstance(obj, list) and self.is_iterable(obj):
obj = list(obj)
return obj