subclassing str

Chris Rebert clp2 at
Sun Nov 7 07:41:44 CET 2010

On Sat, Nov 6, 2010 at 10:43 PM, not1xor1 (Alessandro) <"
"> wrote:
> Hi,
> I'd like to know what is the best way to subclass str
> I need to add some new methods and that each method (both new and str ones)
> return my new type
> For instance I've seen I can do:
> class mystr(str):
>   def between(self, start, end):
>      i = self.index(start) + len(start)
>      j = self.index(end, i) + len(end)
>      return self[i:j], self[j:]
>   def replace(self, old, new='', count=-1):
>      return mystr(str.replace(self, old, new, count))
> I wonder if I have to redefine all methods one by one or if there is a sort
> of hook to intercept all methods calls and just change the return type

You could subclass UserString instead of str; all of UserString's
methods seem to ensure that instances of the subclass rather than just
plain strs or UserStrings are returned. See

But you should also consider whether your additions absolutely *must*
be methods. Merely instead defining some functions that take strings
as parameters is obviously a simpler, and probably more performant,

If you insist on subclassing str, there's no such hook; you'll have to
override all the methods yourself.*

*Well, you could override only the __special__ methods and
__getattribute__(), or use metaprogramming, but at that point you
might as well go the UserString route if possible.

More information about the Python-list mailing list