Test for structure

Martin Miller ggrp1.20.martineau at dfgh.net
Tue Feb 22 04:11:34 EST 2005


At the end of his last post, Steve Bethard wrote:
> 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.

Very interesting, but it also doesn't let you specify a default
argument value...however this gave me the idea that it would be
possible to use the *args idea to greatly simplify the proposed
aslist() function -- when one was needed to allow default argument
values and/or for handling multiple list arguments. Namely:

def aslist(*args):
    return list(args)

def f(arg=None):
    args = aslist(arg)
    ...

f()
f(42)
f('tanstaafl')
f(['spam', 'eggs', 'ham'])

This seems fairly lean and mean, with no if, isinstance, hasattr, or
try/excepts required -- although aslist() might need a check for the
single argument of None case, depending on whether it should return []
or something besides [None] in that situation.

Best,
Martin




More information about the Python-list mailing list