#25218: python_2_unicode_compatible causes infinite recursion when
super().__str__() is called
-------------------------------+--------------------------------------
     Reporter:  jscn           |                    Owner:  nobody
         Type:  Uncategorized  |                   Status:  new
    Component:  Utilities      |                  Version:  1.8
     Severity:  Normal         |               Resolution:
     Keywords:                 |             Triage Stage:  Unreviewed
    Has patch:  0              |      Needs documentation:  0
  Needs tests:  0              |  Patch needs improvement:  0
Easy pickings:  0              |                    UI/UX:  0
-------------------------------+--------------------------------------

Comment (by aaugustin):

 `@python_2_unicode_compatible` changes the implementation of `__str__` and
 `__unicode__` on Python 2. If you want to call the `__str__` method you
 defined in the parent class, you have to call `super(B,
 self).__unicode__()`.

 The following works both on Python 2 and 3:

 {{{
 from __future__ import print_function, unicode_literals

 from django.utils.six import PY3, python_2_unicode_compatible

 @python_2_unicode_compatible
 class A(object):
     def __str__(self):
         return 'a'

 @python_2_unicode_compatible
 class B(A):
     def __str__(self):
         text_method = '__str__' if PY3 else '__unicode__'
         return getattr(super(B, self), text_method)() + 'b'

 print(str(B()))
 }}}

 This version is more readable:

 {{{
 from __future__ import print_function, unicode_literals

 from django.utils.six import PY3, python_2_unicode_compatible

 @python_2_unicode_compatible
 class A(object):
     def text(self):
         return 'a'
     __str__ = text

 @python_2_unicode_compatible
 class B(A):
     def text(self):
         return super(B, self).text() + 'b'
     __str__ = text

 print(str(B()))
 }}}

 This isn't obvious but I can't see a way around it. (I'm the original
 author of this decorator which was added to `six` later.)

--
Ticket URL: <https://code.djangoproject.com/ticket/25218#comment:10>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/062.4a09ae5f5219e81f0c0459f5b1316538%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to