Implicit lists

Mel Wilson mwilson at the-wire.com
Thu Jan 30 13:10:01 EST 2003


In article <m4di3v4koufdbf4e2pvsanegli2kqt48ch at 4ax.com>,
Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> 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
>
[ ... ]
>
>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?

   I don't see anything wrong with this as it stands; it
does just what it says and I presume it does just what you
want.  Nobody has to page 10 or 15 screens up or down in the
source, or consult library docs, to see what's going to
happen.

   The huge responsibility in using a strongly- and
dynamically-typed language is that the program has to line
its data up in the proper types right from the start.
Without that, any attempt later to patch things up is going
to look bizarre.  (e.g. string:  data item or sequence of
characters?  Tune in at 11 ..)

   Whether an arbitrary object with a __getitem__ method or
an iterator, or a __str__ method for that matter, is meant
to be taken as its discrete self or as mere wrapping to
deliver its various contents in a particular situation is an
open question.  Application-dependent, I say.

        Regards.        Mel.




More information about the Python-list mailing list