Implicit lists

Alex Martelli aleax at aleax.it
Fri Jan 31 12:40:32 EST 2003


Donnal Walter wrote:

> functionality. The iteron definition using generators doesn't really work
> for me for some reason. (I confess I don't fully understand generators.) I

Maybe you don't have a:
   from __future__ import generators
at the start of your module?

> I have followed this thread with interest because I need the same kind of
> 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 this is indeed *ALL* you need then the simplest way to
code aslist is probably:

def aslist(x):
    if isinstance(x, (list, tuple)): return x
    return [x]

It's hard to imagine a simpler or more concise way to
express the exact set of functionality given by these
unit tests.

My objection to this approach, based on type-testing,
is that it fails to do what I consider sensible for
args of many OTHER types, such as UserString and the
like.  But if you are adamant that the ONLY types you
want to be left alone are tuples and lists, and EVERY
other type MUST be wrapped up as a 1-item list, which
is at least one way to read these unit tests, then
it's hard to do better than just saying so outright
in the Python source code of function aslist.


Alex





More information about the Python-list mailing list