簡體   English   中英

為什么str(KeyError)會添加額外的引號?

[英]Why does str(KeyError) add extra quotes?

為什么KeyError的字符串表示形式會在錯誤消息中添加額外的引號? 所有其他內置異常只是直接返回錯誤消息字符串。

例如,以下代碼:

print str(LookupError("foo"))
print str(KeyError("foo"))

產生以下輸出:

foo
'foo'

我已嘗試使用其他內置異常( IndexErrorRuntimeErrorException等)的IndexError ,並且它們都返回沒有引號的異常消息。

help(KeyError)說, __str__(...)中定義KeyError ,而不是在LookupError ,它使用在所定義的一個BaseException基類。 這解釋了行為是如何不同的,但沒有解釋為什么KeyError重寫了__str__(...) 關於內置異常的Python文檔並沒有說明這種差異。

針對Python 2.6.6進行了測試

這樣做是為了您可以正確檢測KeyError('') KeyError_str函數源

/* If args is a tuple of exactly one item, apply repr to args[0].
   This is done so that e.g. the exception raised by {}[''] prints
     KeyError: ''
   rather than the confusing
     KeyError
   alone.  The downside is that if KeyError is raised with an explanatory
   string, that string will be displayed in quotes.  Too bad.
   If args is anything else, use the default BaseException__str__().
*/

實際上,如果str(value)是一個空字符串,則traceback打印代碼不會打印異常值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM