Yej*_*ing 7 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])
Run Code Online (Sandbox Code Playgroud)
我的问题是:在哪种情况下将s是Exception的一个实例?
当s是Exception的一个实例时,s既没有str或repr属性.比这种情况发生了.这是正确的吗?
s如果有人使用 Exception 子类调用force_unicode函数并且消息包含 unicode 字符,则将出现异常。
s = Exception("\xd0\x91".decode("utf-8"))
# this will now throw a UnicodeEncodeError
unicode(str(s), 'utf-8', 'strict')
Run Code Online (Sandbox Code Playgroud)
如果块中的代码try失败,则不会将任何内容分配给s,因此 s 将保留最初调用函数时使用的值。
由于Exception继承自object,并且自 Python 2.5 起object就有该__unicode__方法,因此该代码可能存在于 Python 2.4 中,但现在已过时。
更新:打开拉取请求后,此代码现已从 Django 源代码中删除:https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576