#21733: @python_2_unicode_compatible causes infinite recursion when module imported more than once ----------------------------+------------------------- Reporter: ntucker | Owner: nobody Type: Bug | Status: new Component: Utilities | Version: 1.6 Severity: Normal | Keywords: python2.7.3 Triage Stage: Unreviewed | Has patch: 0 Easy pickings: 1 | UI/UX: 0 ----------------------------+------------------------- Sometimes a module that uses @python_2_unicode_compatible is imported multiple times. Possibly because a different pathname is used to import it. When this occurs, it makes __unicode__ be the __str__ function that was originally assigned, which calls __unicode__. So anytime __unicode__ is called on the object, there is infinite recursion.
A simple check whether the __str__ function has already been assigned will prevent setting __unicode__ to the provided recursive function. This will also guard against other cases of multiple @python_2_unicode_compatible calls. {{{ class _STR(object): def __call__(self, obj): return self.__unicode__().encode('utf-8') _str = _STR() def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if six.PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) # this was already applied once if klass.__str__ == _str: return klass klass.__unicode__ = klass.__str__ klass.__str__ = _str return klass }}} I will provide patch if this is accepted. Above is example code. -- Ticket URL: <https://code.djangoproject.com/ticket/21733> 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/050.ba69b34edd2f2031059d5eb5e39c8e6a%40djangoproject.com. For more options, visit https://groups.google.com/groups/opt_out.