Test for structure

Steven Bethard steven.bethard at gmail.com
Mon Feb 21 14:10:26 EST 2005


Martin Miller broke the order of reading again by top-posting:
> However, to handle the more general problem of allow *any* argument to
> be either a single item or a list seems to require a combination of
> both EAPF and LBYL. This is the best solution I've been able to come up
> with so far:
> 
> def asList(arg):
[snip]
>     if arg is None:
>         return []
>     elif isinstance(arg, basestring): # special case strings (to
>                                       # avoid list(<string>))
>         return [arg]
>     else:
>         try:
>             return list(arg)
>         except TypeError:
>             return [arg]
>
[snip]
> Can this be improved or is there anything wrong or overly limiting
> about it?

I don't think you're going to do a whole lot better than that, though 
you can try something like the following if you're really afraid of the 
isinstance:

def aslist(arg):
     # you don't need to test None; it will be caught by the list branch
     try:
         arg + ''
     except TypeError:
         return [arg]
     try:
         return list(arg)
     except TypeError:
         return [arg]

That said, I find that in most cases, the better option is to use *args 
in the original function though.  For example:

     def f(arg):
         args = aslist(arg)
         ...
     f(42)
     f(['spam', 'eggs', 'ham'])

could probably be more easily written as:

     def f(*args):
         ...
     f(42)
     f('spam', 'eggs', 'ham')

Of course this won't work if you have multiple list arguments.

STeVe



More information about the Python-list mailing list