python - 我对这段代码感到困惑

标签 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 会是 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/

相关文章:

java - 如何将平假名转换为半角片假名?

python - 如何仅为列中的特定值生成虚拟变量?

python - 计算所有可能行的差异

python - 人脸识别没有检测到任何 OpenCV

django - django 的 OneToOneField 和 django 的 OneToOneRel 的区别

django - 排除时如何在表单上设置默认值?

python - 在 Django Rest Framework 中使用中介模型序列化 ManyToMany 关系

python - 在 virtualenv 中使用 pip install 时出现 UnicodeDecodeError

python - POS 标记中的字符串索引超出范围

c# - 在 C# 中生成 1 MB(或 n MB)文本文件