join vs instances

Hans Nowak wurmy at
Mon Dec 10 01:03:41 CET 2001

Robin Becker wrote:
> In article <U7QQ7.45073$pP5.5620942 at>, Brad
> Bollenbach <bbollenbach at> writes
> .....
> >Of course it's expected that you can't get away with simply referring to
> >the instance directly and expecting a string to pop out, but can you
> >give an example of a gotcha with a UserString vs. builtin (that is to say,
> >a scenario where you the difference between the two will make it
> >impossible for you to write code that won't break)?
> >
> >
> >Brad
> well since UserStrings can be added to strings
> eg
> >>> from UserString import UserString
> >>> u = UserString('U')
> >>> u+'a'
> 'Ua'
> >>> 'a'+u
> 'aU'
> >>>
> 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. What is the
> primitive implementation of join?

I haven't looked at the C code, but I expect that it wants the types
of the list items to be <type "string">, not "something that behaves
like a string". The latter can often be done in Python code, but I
guess this wasn't an option for built-in (C) functions.
There are other examples of this in Python, for 
example exec, that takes a dictionary but not a UserDict:

>>> from UserDict import UserDict
>>> d = UserDict()
>>> exec 'print "Hello"' in d
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    exec 'print "Hello"' in d
TypeError: exec: arg 2 must be a dictionary or None

There are several workarounds possible, e.g. doing a map(str, lst)
where lst is your list that contains UserString instances, then
joining it.


More information about the Python-list mailing list