On 4 November 2012 13:32, Roy Smith <r...@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.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to