以下内容来自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
会是 Exception 的一个实例?
当 s 是 Exception 的一个实例,并且 s 既没有 str 也没有 repr 属性时。比这种情况发生。这样对吗?
最佳答案
如果有人调用 force_unicode,
s
将是一个异常(exception)带有 Exception 子类的函数,消息包含 unicode 字符。
s = Exception("\xd0\x91".decode("utf-8"))
# this will now throw a UnicodeEncodeError
unicode(str(s), 'utf-8', 'strict')
如果 try
block 中的代码失败,则不会向 s
分配任何内容,因此 s 将保留最初调用函数时使用的内容。
由于 Exception
继承自 object
,而 object
从 Python 2.5 开始就有了 __unicode__
方法,它可能可能是此代码存在于 Python 2.4,现在已过时。
更新: 打开拉取请求后,此代码现已从 Django 源中删除:https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576
关于python - 我对这段代码感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12898212/