Re: Why don't stringobjects have methods?

Tim Peters (tim@ksr.com)
1 Apr 1994 03:55:41 GMT

> ... why is all Python traffic still going to the mailing list
> and none to the newsgroup?

Well, why did you send this to the list instead of the newsgroup <wink>?

Seriously, because of the usual variety of delays in propagation &
overburdened sysadmins, I bet a lot of sites still don't have the group
-- and won't for a few weeks.

> ... Why do stringobjects not have methods?

You answered it later: "because strings are immutable". Ditto tuples,
and ditto ints, long ints, and floats (don't you miss being able to say
"3.pow(5)" too <grin>?).

The interesting question is _why_ strings and tuples (etc) are immutable,
and I don't have an interesting answer to that. Maybe Guido will shed
more light on these decisions?

> listobjects have their own methods so that I can say:
>
> [1, 3, 2].sort()

Note that this example (indirectly) answers your later question, "Why do
the listobject methods always return None?". If list.method() returned
the updated list, then actually using

[1, 3, 2].sort()

as a line of Python would cause

[1, 2, 3]

to get printed. Remember that Python automatically prints every non-None
expression! Changing Python so that list methods returned anything other
than None would cause massive amounts of existing code to start printing
all sorts of unwanted stuff.

> ... I'll often tack things on to the end of a string with:
>
> string = string + char
>
> and this goes and creates a new string object that is the combination
> of the first string and the new char. Wouldn't it be more efficient to
> simply add the char onto the end of the original string?

Pprobably, if there were no other references to the original value of the
string. I say just "probably" because doing a realloc to extend existing
space may (depending on the host) be more expensive than malloc'ing new
space.

> ...
> It would be more useful if [list methods] returned the listobject that
> resulted from the method call. That way I could chain operations
> together like so:
>
> mylist = [1, 2, 3].reverse().append(0).reverse()
>
> and mylist would == [0, 1, 2, 3].

Prediction: You'll lose interest in this after you get more Python
coding under your belt. Why? Because it's rarely useful. E.g., if you
really want to add something to the start of a list (as you're doing in
your example), it's better in every respect to just say

list.insert(0, something)

Similarly, it's almost never useful to apply a list method to a list
literal (so you'll almost always have a name by which to get at the
result later).

an-argument-is-a-connected-series-of-statements-intended-to-establish-a-
proposition-ly y'rs - tim the obscure

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp