__unicode__() works, unicode() blows up.

Joshua Landau joshua.landau.ws at gmail.com
Sun Nov 4 10:04:15 EST 2012


On 4 November 2012 13:32, Roy Smith <roy at panix.com> wrote:

> Environment:
>   Python-2.7.3
>   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
> None
>
> >>> 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.


>>> class Foo:
...     def __unicode__(self): return "Bar" # NOT Unicode
...
>>> Foo().__unicode__()
'Bar'
>>> unicode(Foo())
u'Bar'

unicode(x) calls x.__unicode__() *and then* coerces the result to Unicode.

None cannot be coerced to Unicode.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121104/2c58075a/attachment.html>


More information about the Python-list mailing list