I am confused by this code

Below is the source code for django ( Django-1.41/django/utils/encoding.py );

 try: s = unicode(str(s), encoding, errors) except UnicodeEncodeError: if not isinstance(s, Exception): raise # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII data without special # handling to display as a string. We need to handle this # without raising a further exception. We do an # approximation to what the Exception standard str() # output should be. s = u' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) 

My question is: in which case s will be an instance of Exception?
when s is an instance of Exception and s does not have the str or repr attribute. How does this situation happen. Is it correct?

+7
source share
2 answers

s will be an exception if someone calls the force_unicode function with a subclass of Exception and the message contains Unicode characters.

 s = Exception("\xd0\x91".decode("utf-8")) # this will now throw a UnicodeEncodeError unicode(str(s), 'utf-8', 'strict') 

If the code in the try block fails, nothing will be assigned to s , so s will remain the one from which the function was called.

Since Exception inherits from object , and object has a __unicode__ method with Python 2.5, maybe this code exists for Python 2.4 and is now deprecated.

UPDATE: After opening the transfer request, this code is now removed from the Django source: https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576

+3
source
 >>> from django.utils.encoding import force_unicode >>> force_unicode('Hello there') u'Hello there' >>> force_unicode(TypeError('No way')) # In this case u'No way' 
-one
source

All Articles