我对此代码感到困惑

时间:2012-10-15 14:51:23

标签: python django unicode

以下内容来自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's standard str()
    # output should be.
    s = u' '.join([force_unicode(arg, encoding, strings_only,
        errors) for arg in s])

我的问题是:在哪种情况下,s会成为例外情况的实例?  当s是Exception的一个实例时,s既没有str或repr属性。比这种情况发生了。这是对的吗?

2 个答案:

答案 0 :(得分:3)

如果某人使用Exception的子类调用force_unicode函数并且该消息包含unicode字符,那么

s将是一个例外。

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

如果try块中的代码失败,则不会将任何内容分配给s,因此s将保留最初调用该函数的内容。

由于Exception继承自objectobject自Python 2.5以来已经拥有__unicode__方法,因此可能存在此代码存在于Python 2.4中并且现在已经过时了。

更新: 打开拉取请求后,此代码现已从Django源中删除:https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576

答案 1 :(得分:-1)

>>> 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'
相关问题