Python I';我被这个代码弄糊涂了

Python I';我被这个代码弄糊涂了,python,django,unicode,Python,Django,Unicode,以下内容来自django源代码() 我的问题是:在哪种情况下,s会是异常的实例? 当s是异常的实例,并且s既没有str属性也没有repr属性时。这种情况不会发生。这是否正确?s如果有人使用exception子类调用函数,并且消息包含unicode字符,则该函数将是异常 s = Exception("\xd0\x91".decode("utf-8")) # this will now throw a UnicodeEncodeError unicode(str(s), 'utf-8', 'stri

以下内容来自django源代码()

我的问题是:在哪种情况下,
s
会是异常的实例?

当s是异常的实例,并且s既没有str属性也没有repr属性时。这种情况不会发生。这是否正确?

s
如果有人使用exception子类调用函数,并且消息包含unicode字符,则该函数将是异常

s = Exception("\xd0\x91".decode("utf-8"))
# this will now throw a UnicodeEncodeError
unicode(str(s), 'utf-8', 'strict')
如果
try
块中的代码失败,则不会向
s
分配任何内容,因此s将保留最初调用函数时使用的内容

由于
异常
继承自
对象
,并且
对象
自Python2.5以来具有
\uuuuuUnicode\uuuuuUnicode>方法,因此可能是Python2.4中存在此代码,现在已过时

更新:
打开pull请求后,此代码现在已从Django源代码中删除:

我可以用Python编写
raise“a_string”
?raise的唯一参数表示要引发的异常。这必须是异常实例或异常类(从异常派生的类)。但在s=unicode(str(s),编码,错误)中。str将返回一个字符串。因此,在这个语句之后,s将是u'No way'。谢谢,我认为当s是异常的实例,并且s没有str或repr属性时。这种情况不会发生。这是正确的。
s = Exception("\xd0\x91".decode("utf-8"))
# this will now throw a UnicodeEncodeError
unicode(str(s), 'utf-8', 'strict')
>>> 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'