【问题标题】:I'm confused by this code我对这段代码感到困惑
【发布时间】:2012-10-05 13:54:49
【问题描述】:

以下来自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 属性。比这种情况发生。是这样吗?

【问题讨论】:

  • 我可以用 Python 写 raise "a_string" 吗?
  • raise 的唯一参数表示要引发的异常。这必须是异常实例或异常类(从 Exception 派生的类)。

标签: python django unicode


【解决方案1】:

如果有人使用 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 继承自object,并且object 从Python 2.5 开始就有__unicode__ 方法,因此该代码可能存在于Python 2.4 并且现在已过时。

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

【讨论】:

  • 谢谢,我认为当 s 是 Exception 的一个实例,并且 s 既没有 str 也没有 repr 属性。比这种情况发生。是对的。
【解决方案2】:
>>> 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'

【讨论】:

  • 但在 s = unicode(str(s), encoding, errors) 中。 str(s) 将返回一个字符串。所以在这个声明之后 s 将是 u'No way'。
猜你喜欢
  • 2016-06-22
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2015-07-12
  • 2018-09-29
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
相关资源
最近更新 更多