function that modifies a string
Diez B. Roggisch
deets at nospam.web.de
Mon Jul 10 13:30:09 EDT 2006
>>> Arrays of chars are dangerous. If you insist, use Python lists of
>>> Python "chars" (strings of length 1).
>> Why are they more dangerous than a self-written mutable string?
>
> I didn't say that. I meant that arrays in the C++ sense are dangerous.
So what? Python's arrays are backed by arrays of the type they have,
whereas lists are represented by arrays of python objects. Both arrays
of some kind. Both hide this behind a convenient API whcih don't put any
responsibility on the programmer's shoulder. Now I ask again: where is
that dangerous, or more dangerous than writing your own mutable string?
> C++ offers pass by value options. That makes it so you never need to
> worry about messing up data that doesn't belong to you unless you
> explicitly pass by reference. Python doesn't do this for you. Thus, a
> mutable string class in Python requires a great deal more care since
> you need to make copies of every string in every function in order to
> prevent changes in one object's string from affecting another.
While you are technically correct, it strikes me odd that someone uses
mutable strings in a scenario where he also wants copy-semantics for
pass-by-value. That is plain stupid: create O(n) complexity to achieve
what immutable strings buy you for O(1).
So: Yes, mutable strings are dangerous. Use them only when their
benefits outweigh their risks. But you argumentation regarding C++ is
odd to say the least. Especially since the cited call-by-value semantics
doesn't come for free - designing and implementing assignment operators
and copy-constructors is a daunting task in itself.
And if you WANT to use mutable strings with a call-by-value semantic in
python, a simple decorator that scans arguments for mutable strings
could help you there.
Diez
More information about the Python-list
mailing list