__unicode__() works, unicode() blows up.

Roy Smith roy at panix.com
Sun Nov 4 14:32:18 CET 2012

  Ubuntu Precise
  mongoengine 0.6.20

I have a class which includes a __unicode__() method:

class User(mongoengine.Document):
    def __unicode__(self):
        return self.username

If I create an instance of this class by calling the constructor 
directly, self.username is None.  When I pass that to unicode(), it 
blows up.  However, calling __unicode__() directly, works as expected:

>>> u = User()
>>> print u.username

>>> print u.__unicode__()

>>> 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.

More information about the Python-list mailing list