Testing for a list
Antun Karlovac
antun at antunkarlovac.com
Mon Mar 10 13:48:33 EST 2003
Thanks Mark!
Python doesn't have a builtin method for doing this then, right?
-Antun
> -----Original Message-----
> From: Mark McEahern [mailto:marklists at mceahern.com]
> Sent: Monday, March 10, 2003 9:43 AM
> To: Antun Karlovac; python-list at python.org
> Subject: RE: Testing for a list
>
>
> [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