Implicit lists
Martin Miller
mmiller at tx3_DELTHIS_.com
Mon Feb 3 15:08:41 EST 2003
Here's a working documented version of asList, for any of those to whom
it might not be so "obvious". It can easily be customized to handle
various types a special cases (as shown for tuples and the value None).
HTH,
Martin
> def asList(arg):
> """Makes sure the argument it is passed is a Python list. If it is
> it is just returned, otherwise a degenerate list is created and
> returned with the single item in it.
>
> asList() can used to create flexible interfaces which allow
> arguments to be passed to them that are either single items or lists
> of items. By applying this function before using the values in
> arguments, single and multi-valued cases can be handled by general
> list-handling code in the function or method.
>
> As a special case, a single argument with the value None is converted
> into an empty list (instead of converted into the list [None]).
>
> asList(arg) ==> list
> """
> import types # Standard Python types module
>
> if type(arg) is types.ListType: # Nothing to do
> return arg
> elif type(arg) is types.TupleType:# Convert tuples to lists
> return list(arg)
> elif type(arg) is types.NoneType: # Special case, treat None as []
> return []
> else: # Convert item to list of one item
> return [arg]
>
> if __name__ == "__main__":
>
> def example(items=None):
> """Sample function that can be called with an argument
> that can be a individual or list of items.
> """
> itemList = asList(items)
> if itemList:
> print "example() called with argument containing", len(itemList), "thing(s)"
> else:
> print "example() called with empty list or None argument"
> i = 0
> for item in itemList:
> print " item[" + str(i) + "] = " + repr(item)
> i += 1
> print
>
> example(42)
> example((1,2,3))
> example([4,5,6,7])
> example(["aaa", 111, (4,5), 2.01])
> example(None) # Note that this will become an empty list
> example() # same in this case
====================
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.
>
> If it turns out (as would seem to be the case) that what you
> need is actually an iterator (since you want to treat tuples
> as "lists", you ain't gonna be able to append, sort, &c
> anyway) then I'd name the auxiliary function "iteron" or
> something like that. In my experience, what I generally
> want is:
> treat strings, and all string-like objects, as non-sequences
> otherwise, iterate directly on sequences and other iterables
> "other iterables" is debatable (files, dictionaries, ...) but
> that's how I've generally found things work best -- easy enough
> to tweak it to your liking otherwise. So, for example:
>
> def iteron(something):
> # string-like objects: treat as non-sequences
> try: something+''
> except TypeError: pass
> else:
> yield something
> return
> # other sequences
> try:
> for x in something: yield x
> except TypeError:
> yield something
>
>
> Alex
>
More information about the Python-list
mailing list