2015-10-15 92 views
1

我發現ValueErrorKeyError之間存在不一致。前者將\n視爲換行符;後者將其視爲原始文本。這種行爲是否正常/預期?Python KeyError和ValueError不一致?

TeX_dict是一個字典,用於將部分字典鍵轉換爲TeX格式化字符串,用於生成繪圖。 part就是這樣一個部分。以下是part的兩個示例:

  • a&b已在字典中成功拆分並轉換。
  • a,b&c不是。

當我提出一個ValueError時,\n換行符會生成一個新行。當我提出KeyError時,他們沒有。

geo_split = lambda thing: '\&'.join([ 
             TeX_dict[x] 
             for x in thing.split('&') 
            ]) 

try: 

    TeX = geo_split(part) 

except KeyError: 

    msg = ("You have programmed limited functionality for " 
      "geometric mean keys. They can only handle species " 
      "that are hard coded into " 
      "``pccv.TeX_labels.axis_labels``.\n\n" # 
      "The following part failed: {}\n" 
     ).format(part) 

    raise ValueError(msg) # If this is KeyError, the new lines don't print. 

這裏是從每一個輸出樣本:

ValueError: You have programmed limited functionality for geometric mean keys. 
They can only handle species that are hard coded into 
``pccv.TeX_labels.axis_labels``. 

KeyError: 'You have programmed limited functionality for geometric mean keys. 
They can only handle species that are hard coded into 
``pccv.TeX_labels.axis_labels``.\n\nThe following part failed: a,p1&p2\n' 

回答

3

這是KeyError實現的特點。

/* 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__(). 

你可以解決它通過傳遞東西,覆蓋__repr__

class Wrapper(str): 
    def __repr__(self): 
     return str(self) 

raise KeyError(Wrapper('hello\nthere'))