Implicit lists
Alex Martelli
aleax at aleax.it
Thu Jan 30 10:19:30 EST 2003
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