Implicit lists
Donnal Walter
donnalcwalter at yahoo.com
Fri Jan 31 11:14:55 EST 2003
"Alex Martelli" wrote:
> Dale Strickland-Clark wrote:
>
> > In many places, often small utility functions, I find myself using the
> > form:
> >
> > lst = maybeAnArg
> > if type(lst) not in (list, tuple)
> > lst = [lst]
> > for x in lst:
> > whatever
> >
> > or
> >
> > lst = maybeAnArg
> > if type(lst) not in (list, tuple)
> > lst = [lst]
> > mangle = [x for x in lst if whatever]
> >
> >
> > In other words, I want to be able to treat an argument of arbitrary
> > type as a list of 1 if it isn't already a list.
> >
> > Has anyone got a neater way of doing this?
>
> Sure:
>
> for x in aslist(list):
> whatever(x)
>
>
> How aslist is written is obviously quite secondary (at least,
> I _hope_ that's obvious...) -- all of its USES will be just as
> neat as the above example.
> ...
I have followed this thread with interest because I need the same kind of
functionality. The iteron definition using generators doesn't really work
for me for some reason. (I confess I don't fully understand generators.) I
would settle for a function aslist that would meet the following unit tests:
class MyObject(object): pass
class test_aslist(unittest.TestCase):
def test_string(self):
x = 'spam' # arg
y = aslist(x) # test function
z = [x] # target
self.assertEquals(y, z)
def test_tuple(self):
x = ('spam', 'eggs') # arg
y = aslist(x) # test function
z = ['spam', 'eggs'] # target
self.assertEquals(y, z)
def test_list(self):
x = ['spam', 'eggs'] # arg
y = aslist(x) # test function
z = x # target
self.assertEquals(y, z)
def test_instance(self):
x = MyObject() # arg
y = aslist(x) # test function
z = [x] # target
self.assertEquals(y, z)
if __name__ == '__main__':
unittest.main()
Thanks.
Donnal Walter
Arkansas Children's Hospital
More information about the Python-list
mailing list