subclassing str

Russell Blau russblau at
Tue Sep 14 15:30:43 CEST 2004

"Thomas Lotze" <thomas.lotze at> wrote in message
news:pan.2004. at
> For an application, I need a special string-like object. It has some
> specific semantics and behaves almost like a string, the only difference
> being that it's string representation should be somewhat fancy. I want
> to implement it as a subclass of str:
> That is, I want to be able to make a SpecialString from anything that has
> a string representation, but at the same time leave a SpecialString
> untouched in the process. After all, it already is and gets formatted as a
> SpecialString.
> I tried the following:
> class SpecialString(str):
> def __str__(self):
> return "(" + self + ")"
> This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected.
> Does this accumulation of braces happen in the string itself, or does the
> formatting routine get called several times at each str() call? How to fix
> it, depending on the answer?
> I tried reimplementing __init__() in order to treat the case that a
> SpecialString is given to the constructor, but with little success.

I think you need to use __new__() instead of __init__(), like so:

>>> class SpecialString(str):
    def __new__(cls, seq):
        if isinstance(seq, SpecialString):
            return str.__new__(cls, str(seq)[1:-1])
            return str.__new__(cls, seq)
    def __str__(self):
        return "(" + self + ")"

>>> x = SpecialString("foo")
>>> y = SpecialString(x)
>>> print x
>>> print y

For more info, see

I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.

More information about the Python-list mailing list