[英]I'm confused by this code
以下是來自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屬性。 比這種情況發生了。 這是正確的嗎?
如果有人使用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
>>> 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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.