gah! I hate the new string syntax

Steve Holden sholden at holdenweb.com
Tue Mar 13 02:31:01 EST 2001


"Amit Patel" <amitp at Xenon.Stanford.EDU> wrote in message
news:98iqo2$56o$1 at nntp.Stanford.EDU...
> Alex Martelli <aleaxit at yahoo.com> wrote:
> | "Amit Patel" <amitp at Xenon.Stanford.EDU> wrote in message
> | news:98elrk$li8$1 at nntp.Stanford.EDU...
> |     [snip]
> | > What I mean to say is that I cannot write new methods on strings.  So
> |
> | Perfectly true, just as you cannot on dictionaries, lists, tuples,
> | file objects, and so on.  Only classes and extension-classes
> | are extensible (by inheritance and overriding), not types.
>
> Even if strings were a class, and I could extend it, it is NOT the
> thing to do to add new functionality like capitalize().  Suppose
> strings do not have a capitalize method, and I want to add one.  And
> suppose strings are classes and can be extended.  If I wrote:
>
>   class MyString(string):
>      def capitalize(self):
>         ...
>
>
> then I can only capitalize strings I created!  I can't take
> ' '.join(['lister', 'is', 'a', 'smeghead'] and run .capitalize() on
> it -- because it's an ordinary string and not a MyString.
>
> The advantage of method functions like string.capitalize is that they
> do not require me to change something I can't change (the string
> type).  I can write capitalize(x) when x is a string.  I can't write
> x.capitalize() when x is a string.
>
Well, being pedantic, of course, the capitalize() method is already
provided:

>>> x = "that seems wrong"
>>> x.capitalize()
'That seems wrong'

However, your point is valid for a general transmogrify() method.

> Defining methods is like running things as root.  Yes, you sometimes
> need to do it, but it's best to limit yourself to only those things
> that need superuser access.  Run as much as you can as non-root.  And
> IMO that goes for methods and functions too -- string type methods are
> "root" (where "root" = "Guido & pals") and have access to the
> internals of a string, whereas functions on strings are user-level and
> go through the abstractions.
>
But surely the idea of inheritance is precisely that if you want
self-capitalizing strings you should be prepared to subclass the string
class. Or, in Python (since strings are a type) to wrap them then subclass
the wrapper.

The type/class dichotomy can lead to awkwardness, but I've seen no proposal
to get rid of it before Python 3, probably way in the future.

regards
 Steve






More information about the Python-list mailing list