7

以下は、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 属性もない場合。この状況よりも。これは正しいですか?

4

2 に答える 2

3

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 は関数が最初に呼び出されたもののままになります。

はからException継承されobject、メソッドobject__unicode__Python 2.5 から存在しているため、このコードは Python 2.4 用に存在し、現在は廃止されている可能性があります。

更新: プル リクエストを開いた後、このコードは Django ソースから削除されました: https://github.com/django/django/commit/ce1eb320e59b577a600eb84d7f423a1897be3576

于 2012-10-15T15:00:05.443 に答える
-1
>>> 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'
于 2012-10-15T15:03:26.470 に答える