Iteration of strings

Bjarke Dahl Ebert bebert at tiscali.dk
Sat Nov 23 09:11:17 EST 2002


"Terry Reedy" <tjreedy at udel.edu> wrote in message
news:faWdnQY6h6rRT0OgXTWcqw at comcast.com...

> > 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.

Yes they do - the expectation is just not explicitly stated, and it is often
more "vague" than any simple formal type system could express.

> > 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.

But even though we have dynamic types, there is nothing wrong with having
*strong* dynamic types, i.e. not anything applies to anything.
I don't want everything to automatically convert into something that any
given operation can work on. Then we end up as in Perl, where strings and
numbers are somewhat magically converted into each other.

> 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.

Yes, it's probably good to explicitly limit the types of arguments (or other
objects gotten from "somewhere" during function execution). E.g., assert
isinstance(...).
That catches many error early in the call stack, instead of giving strange,
incomprehensible errors deeper down.

> 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
> ;<).

Yes, that can lead to suprizes too. IMHO, it would be better to require the
more explicit "for key in somedict.iterkeys():".
But of course, the new syntax (or actually, semantics of dict.__iter__)
leads to more brevity, when we know what we are doing :-).


Bjarke







More information about the Python-list mailing list