join vs instances

Jason Orendorff jason at jorendorff.com
Mon Dec 10 00:37:03 CET 2001


Robin Becker wrote:
> I had expected that the join operation would also apply to UserStrings
> somehow or that there would be some magic method that would allow join
> to be applied to user strings, but I can't find out how.  [...]

class MyStr(str):
    def my_method(self):
        return MyStr("<<" + self + ">>")

This works in Python 2.2.  Older versions won't let you do that.
UserString is not nearly as versatile.

  >>> x = MyStr("abcdefg")
  >>> ','.join(['w', x, 'y', 'z'])    # hey, it works!
  'w,abcdefg,y,z'
  >>> x.my_method()
  '<<abcdefg>>'

If you're really interested in the C source code to join(), start here
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/~checkout~/python/python/dist
/src/Objects/stringobject.c?rev=2.146&content-type=text/plain
and search for "join".  You'll find it around line 1166.

--
Jason Orendorff    http://www.jorendorff.com/





More information about the Python-list mailing list