subclassing str

Thomas Lotze thomas.lotze at gmx.net
Tue Sep 14 08:56:23 EDT 2004


Hi,

first of all, cheers to everyone, this is my first clp posting.

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:

class SpecialString(str):
	whatever

Using instances

x = SpecialString('foo')
y = SpecialString(x)

I want to get this behaviour:

str(x) => '(foo)'
str(y) => '(foo)'

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
guess that something like

	def __init__(self, obj):
		if isinstance(obj, SpecialString):
			self = raw(obj)
		else:
			self = obj

is needed, with raw() giving me the string without added parentheses,
bypassing the string representation. If this approach is sensible, what
would raw() look like?

Or is it best not to mess with __str__() at all, and introduce a render()
method?

Thanks & greetings,
Thomas




More information about the Python-list mailing list