[英]ValueError compatibility and multi-line string aesthetics?
我試圖以一種簡潔,簡潔的方式編寫ValueError消息:
raise ValueError("Model Architecture Not Recognized. Please ensure that your model's filename contains either"
""" "vgg" and "16" for a 16 layer VGG model, "vgg" and "19" for a 19 layer VGG model, or "nin" for a Network"""
" In Network model. Note that filenames are not case sensitive.")
這對Python 2.7和Python 3都適用嗎? 有沒有更好的方法來顯示多行錯誤消息? 在錯誤消息所使用的字符串之間不使用+
會有任何問題嗎?
這對Python 2.7和Python 3都適用嗎?
是的,字符串文字串聯在Python 2和Python 3中的工作方式相同。
有沒有更好的方法來顯示多行錯誤消息?
是。 特別是因為實際上這並不是多行錯誤消息。 見下文。
在錯誤消息所使用的字符串之間不使用+會有任何問題嗎?
從語義上講,不。 相鄰的字符串文字被串聯成一個字符串值。 用+
分隔的字符串文字定義了一堆單獨的字符串值,然后要求Python在運行時將它們連接起來。 但是,由於編譯器知道表達式僅由不可變的常數組成,因此它將它們折疊為一個值。 一二
但務實的是,很難讀取這樣的代碼(尤其是當您嘗試在80列的顯示器(例如典型的終端模式編輯器或Stack Overflow)上閱讀該代碼時。 作為讀者,我怎么知道您打算將三個字符串文字連接成一個值,還是要將三個字符串文字之間帶有逗號作為三個單獨的值傳遞給ValueError
構造函數? 好吧,如果我仔細看一下,再想一想,將另外兩個字符串作為額外參數傳遞給ValueError
沒什么意義(盡管這是合法的),並且這些空格使它們看起來像是字符串一樣,依此類推...但是如果我不仔細看就能理解您的代碼,將窗口向右滾動並考慮它會更好。 因此,有時值得使用+
或類似反斜杠連續之類的丑陋形式來避免這種混淆。
如上所述,您尚未生成多行字符串。 琴弦被串聯成一條巨線。 似乎您已經知道這一點,或者您不會在第二個和第三個文字的開頭加上空格。
如果您確實需要多行字符串,則可以通過在適當的位置添加\\n
字符來實現。
但是編寫多行字符串要容易得多:
raise ValueError("""Model Architecture Not Recognized. Please ensure that your model's filename contains either
"vgg" and "16" for a 16 layer VGG model, "vgg" and "19" for a 19 layer VGG model, or "nin" for a Network
In Network model. Note that filenames are not case sensitive.""")
或者,甚至更好的方法是使用textwrap
,這樣您可以編寫在源代碼中看起來不錯但在輸出上看起來也不錯的東西:
raise ValueError(textwrap.fill(textwrap.dedent("""
Model Architecture Not Recognized. Please ensure that your model's
filename contains either "vgg" and "16" for a 16 layer VGG model,
"vgg" and "19" for a 19 layer VGG model, or "nin" for a Network
In Network model. Note that filenames are not case sensitive.
"""))
但是,如果您希望將其作為回溯的一部分進行打印,而不是except Exception as e: print(e)
,那么它仍然看起來很時髦:
ValueError: Model Architecture Not Recognized. Please ensure that your model's
filename contains either "vgg" and "16" for a 16 layer VGG model,
"vgg" and "19" for a 19 layer VGG model, or "nin" for a Network In
Network model. Note that filenames are not case sensitive.
更好的解決方案可能是編寫一個簡短的錯誤字符串,再加上一個單獨的長長的(多行,如果需要的話)描述字符串。 您甚至可以通過轉儲長字符串來制作自己的ValueError
子類來表示自身。 您甚至可以將textwrap
內容放入子類中。 所以,你會寫,說:
raise ModelArchitectureError(
"Model Architecture Not Recognized.",
"""Please ensure that your model's
filename contains either "vgg" and "16" for a 16 layer VGG model,
"vgg" and "19" for a 19 layer VGG model, or "nin" for a Network
In Network model. Note that filenames are not case sensitive.
"""))
或者,甚至更好的是,為ModelArchitectureError
的構造函數設置這些默認值,因此您可以執行以下操作:
raise ModelArchitectureError()
1.當然,Python 不需要這種常量求值,而只是允許它。 CPython 2.7和3.7,PyPy 6 2.7和3.5以及Jython 2.7都可以做到,但是其他一些實現可能不行。 在那種情況下, +
版本將具有相同的最終用戶可見效果,但是要花更多時間和臨時內存(可能還需要緩存空間和string-intern-table空間)。
2.如果您編寫了一個導入鈎子,然后在將其傳遞給編譯器之前先在源代碼,令牌或AST級別上轉換代碼,則可以想象兩者可能是不同的,因為在編譯器/優化器進入編譯器/優化器之前,它們不會變得相同。它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.