[Tutor] parsing configuration files

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Dec 22 22:33:56 EST 2003



On Mon, 22 Dec 2003, Lloyd Kvam wrote:

> >>There's a subtle type error going on, and it has to do with 'data'.
> >
> > Hmm. I guess this is one of the disadvantages of Python's relatively
> > weak typing.
>
> I don't think it is weak typing so much as the fact that a string, list
> and tuple are all sequences.


Hi Daniel,

I should have been more careful with my phrasing.  What I meant was that
there was a "conceptual" type error in that code.  The bug is one of
semantics, and that's something that computers won't figure out for a
while.

As far as Python is concerned, all the typing there was fine.

Looking back at an example:

###
>>> l = []
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> l1.extend(l2)
>>> l1
[1, 2, 3, 4, 5, 6]
###

the extend() method takes in a 'sequence' as its argument, and adds all
the elements in that sequence in.  Actually, I'm not quite telling the
truth again.  The extend() method actually wants an 'iterable'.  An
'iterable' is anything that can return single elements at a time.


Anyway, Python treats strings as a sequence of characters --- that's what
allows us to do things like:

###
>>> for letter in 'hello':
...     print letter
...
h
e
l
l
o
###


As a consequence of this, if we extend a list by a string, what we're
really asking Python to do is add every element --- every character --- as
an element of that list.  In fact, it's useful for it to do this!

###
>>> buffer = list("hello")
>>> buffer
['h', 'e', 'l', 'l', 'o']
>>> buffer.extend("world")
>>> buffer
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
###

(Instant java.lang.StringBuffer, for folks who are familiar with Java.
*grin*)


So the original "buggy" code is perfectly correct in terms of typing.  If
it were not, we would have seen TypeError exceptions flying around, and
would have caught the bug sooner.  The problem is that the code is doing
exactly what it is told, and not what we really mean.  *grin*


Hope this clears things up!




More information about the Tutor mailing list