__unicode__() works, unicode() blows up. (Never mind!)

Aahz aahz at pythoncraft.com
Sun Nov 4 18:13:47 CET 2012

In article <roy-30BA92.08410804112012 at news.panix.com>,
Roy Smith  <roy at panix.com> wrote:
>In article <roy-90D9A2.08321804112012 at news.panix.com>,
> Roy Smith <roy at panix.com> wrote:
>> >>> print u.__unicode__()
>> None
>> >>> print unicode(u)
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: coercing to Unicode: need string or buffer, NoneType found
>> What's going on here?  I thought 
>> (http://docs.python.org/2/library/functions.html#unicode) the latter two 
>> calls should be identical, but obviously they're not.
>Why is it, that no matter how long you stare at a problem, the answer 
>comes to you moments after you hit the Post button? :-)
>The problem is that __unicode__() is supposed to return a Unicode 
>object, and unicode() enforces that.  The fix is to change:
>    def __unicode__(self):
>        return self.username
>to be:
>    def __unicode__(self):
>        return unicode(self.username)
>This never got noticed before because normally, self.username already is 
>a unicode string, so it just works.

You apparently need more coffee when programming after waking up!  (Or
even worse, staying up all night.)
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"....Normal is what cuts off your sixth finger and your tail..."  --Siobhan

More information about the Python-list mailing list