简体   繁体   中英

I'm confused by this code

This following is from the django source code ( 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's 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 will s be an instance of Exception?
when s is an instance of Exception, and s have neither str or repr attribute. Than this situation happen. Is this right?

s will be an exception if someone called the force_unicode function with a subclass of Exception and the message includes 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 then nothing will be assigned to s , so s will remain what the function was initially called with.

Since Exception inherits from object , and object has had the __unicode__ method since Python 2.5, it might be the case that this code existed for Python 2.4 and is now obsolete.

UPDATE: After opening a pull request, this code has now been removed from the Django source: https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576

>>> 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM