Testing for a list
Mark McEahern
marklists at mceahern.com
Mon Mar 10 12:43:12 EST 2003
[Antun Karlovac]
> Is there a way to test if a variable is a list?
>
> i.e.
>
> a = []
>
> If I have 'a', I need to know whether it is a list or a string.
Here's a unittest-demo of the code Alex posted here:
http://groups.google.com/groups?selm=hi018.2207%24Qu1.90579%40news2.tin.it
#!/usr/bin/env python
import unittest
def issequence(item):
try:
item + ''
except TypeError:
try:
for x in item:
break
except TypeError:
return False
else:
return True
else:
return False
class test(unittest.TestCase):
def test_unicode(self):
u = u'test'
self.failIf(issequence(u))
def test_string(self):
s = 'string'
self.failIf(issequence(s))
def test_list(self):
l = []
self.failUnless(issequence(l))
def test_tuple(self):
t = ()
self.failUnless(issequence(t))
if __name__ == '__main__':
unittest.main()
-
More information about the Python-list
mailing list