Python 如何在异常消息中包含外部类?
当使用内部类作为异常时,我希望获得更准确的异常消息。例如:Python 如何在异常消息中包含外部类?,python,exception,inner-classes,Python,Exception,Inner Classes,当使用内部类作为异常时,我希望获得更准确的异常消息。例如: import csv class CsvReader: # pylint: disable=too-few-public-methods """ Handles reading of the CSV input file """ def __init__(self): self.file_name = 'test.csv'
import csv
class CsvReader: # pylint: disable=too-few-public-methods
""" Handles reading of the CSV input file
"""
def __init__(self):
self.file_name = 'test.csv'
self.header = ''
def read_file(self):
""" Reads the CSV file.
"""
with open(self.file_name) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
line_count = 0
for row in csv_reader:
if len(row) == 0:
continue
if len(row) != 5:
raise self.BadRowFormat(row, line_count)
if line_count == 0:
self.header = row.copy() # clone the list
line_count += 1
print(f'Processed {line_count} lines.')
class BadRowFormat(Exception):
""" Exception thrown when a line of the CSV file does not satisfy the
expected format
"""
def __init__(self, row, line_count):
super().__init__(f'Could not parse line {line_count}: {", ".join(row)}. '
f'Expected 5 fields, got {len(row)}')
def main():
""" Main function
"""
csv_reader = CsvReader()
csv_reader.read_file()
main()
以及输入文件test.csv
:
Name,Places,Adult price,Pensioner price,Children price
B1,50,100,60,50
B2,100,120,70,60
B3,150,125,75,60
1
运行此脚本时,会收到以下异常消息:
File "./t.py", line 43, in <module>
main()
File "./t.py", line 40, in main
csv_reader.read_file()
File "./t.py", line 22, in read_file
raise self.BadRowFormat(row, line_count)
__main__.BadRowFormat: Could not parse line 4: 1. Expected 5 fields, got 1
文件“/t.py”,第43行,在
main()
文件“/t.py”,第40行,主
csv_reader.read_文件()
文件“/t.py”,第22行,在read_文件中
raise self.BadRowFormat(行、行计数)
__main.BadRowFormat:无法分析第4行:1。预期5个字段,得到1个
是否可以获得比以下内容更具描述性的异常消息:
\uuuuu main\uuuuuu.BadRowFormat
?我希望有类似于CsvReader.BadRowFormat
或\uuuu main\uuuuuu.CsvReader.BadRowFormat
的内容,向用户显示异常源于CsvReader
类。您可以使用以下结构:
class BadRowFormat(Exception):
""" Exception thrown when a line of the CSV file does not satisfy the
expected format
"""
def __init__(self, classname, row, line_count):
super().__init__(f'{classname}: Could not parse line {line_count}: {", ".join(row)}. '
f'Expected 5 fields, got {len(row)}')
然后用以下词语来称呼它:
self.BadRowFormat(self.__class__.__name__, row, line_count)
这样可以在错误中添加类名。希望我正确地理解了您的问题。谢谢,但是
BadRowFormat
不应该已经知道它是CsvReader
的一个内部类吗?我可能错了,但是看看Python中的异常实现,它只会根据这里和这里的代码得到类型名的最右边部分。虽然类型确实知道它是嵌套的,但消息不会显示它。也许值得为此提出一个github问题;如果您想向用户展示您的CsvReader
类,那么它应该有一个对该类的引用。在另一个类中定义异常类不会自动修改其名称或异常消息。我个人会在CsvReader
之外定义此异常,并将其称为CsvReaderParseError
或类似的名称。