我对这段代码感到困惑

问题描述:

以下是来自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会是异常的一个实例吗?
当s是Exception的一个实例时,s不具有str或repr属性。比这种情况发生。这是正确的吗?

+0

我可以写'养 “在此处a_string”'在Python: 打开拉请求后,该代码现在已经从Django的源删除? –

+0

引发的唯一参数表示要引发的异常。这必须是异常实例或异常类(从Exception派生的类)。 – Yejing

s将是一个例外,如果有人用Exception的子类调用force_unicode函数并且该消息包含unicode字符。

s = Exception("\xd0\x91".decode("utf-8")) 
# this will now throw a UnicodeEncodeError 
unicode(str(s), 'utf-8', 'strict') 

如果try块中的代码失败,那么什么都不会被分配到s,所以S也会一直是函数最初调用。

由于Exceptionobject,并且object继承有过__unicode__方法因为Python 2.5,则可能是存在的Python 2.4的代码,现在已经过时的情况。

UPDATE:https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576

+0

谢谢,我想当s是Exception的一个实例,并且s既没有__str__也没有__repr__属性。比这种情况发生。是对的。 – Yejing

+0

只有消息具有Unicode字符。 –

+0

我认为这只适用于2.5之前的Python版本。 –

>>> 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' 
+0

但是在s = unicode(str(s),encoding,errors)中。 str(s)将返回一个字符串。所以在这个陈述之后,s将会是'不'。 – Yejing