Iteration of strings

Terry Reedy tjreedy at udel.edu
Fri Nov 22 20:08:12 EST 2002


"Bjarke Dahl Ebert" <bebert at tiscali.dk> wrote in message
news:DEyD9.31221$HU.2267489 at news010.worldonline.dk...
>When writing small scripts in Python, I often make the same error:

> Some function expects a list of strings,

Here is the root of your problem.  In a real sense, Python functions
have no expectation as to type.  While you may *intend* for your
function to work with a limited set of types, the interpreter will
pass in anything the caller sends and the function will accept and try
to work with anything it gets.  There is no shield of parameter type
declarations.  There is also no straightjacket of type declarations.

>     for elem in thestringlist: ...
>
> Often, this function is somehow called with a string,
> instead of a list of  strings.

Python's polymorphic genericity is wonderful when it does just what
you want.  It's a slight pain when it doesn't.  Then you have to
explicitly block or modify 'incorrect' inputs or live with the
consequences.  This is a general part of Python programming and not
specific to your particular bugaboo.  Start your function with the
line

  if isinstance(strlist, str): strlist = [strlist]

> This is unfortunate, because in a sense, a string is also a list of
strings!

Not just 'in a sense'.  Substituting 'sequence' for 'list', this is a
defined feature of the anguage.  If one wants the polymorphism, this
is fortunate, not unfortunate.  I consider being able to iterate
through strings a great feature.

Again, the pain/gain of polymorphism is general to Python.  Consider

def multadd(a,b,c): return a*b+c

The fact that seq+seq and int*seq work instead of raising exceptions
is also 'unfortunate' if you consider multadd(3,'a','b') = 'aaab' to
be a bug.  Should we outlaw these operations also?

<...>

> What do you think?

Negative.  Polymorphism is part of the heart of the language.   An
extra line of code here and there to limit it when not wanted is part
of the price of the benefits.  And the trend is to increase it.  For
instance, 'for key in somedict:' just became legal in 2.2.  It
previously would have raised an exception.  So now you can also worry
about what happens if 'somestringlist' is somehow passed in as a dict
;<).

Terry J. Reedy





More information about the Python-list mailing list