[Tutor] How to return a list in an exception object?

Peter Otten __peter__ at web.de
Wed Jun 17 18:26:46 CEST 2015


David Aldrich wrote:

> Hi
> 
> I have a function that compares a set of files with a reference set of
> files.  All files are compared and then, if any differences were found, an
> exception is raised:
> 
> class Error(Exception): pass
> 
> def check_results(file_list):
> 
>     <snip>
> 
>     if isDifferent:
>         raise Error('One or more result files differ from the reference
>         result files')
> 
> I would like to pass back to the caller a list of the files that failed.
> How would I include that list in the exception object?

While you can pass them as just another argument

>>> class UnexpectedFileContents(Exception):
...     pass
... 
>>> try:
...     raise UnexpectedFileContents("Some files differ from the reference", 
["foo.txt", "bar.py", "baz.rst"])
... except UnexpectedFileContents as err:
...     print(err)
...     print("The problematic files are")
...     print("\n".join(err.args[1]))
... 
('Some files differ from the reference', ['foo.txt', 'bar.py', 'baz.rst'])
The problematic files are
foo.txt
bar.py
baz.rst

it's probably a good idea to put in a bit more work:

>>> class UnexpectedFileContents(Exception):
...     def __init__(self, message, files):
...         super().__init__(message)
...         self.files = files
... 
>>> try:
...     raise UnexpectedFileContents("Some files differ from the reference", 
["foo.txt", "bar.py", "baz.rst"])
... except UnexpectedFileContents as err:
...     print(err)
...     print("The problematic files are")
...     print("\n".join(err.files))
... 
Some files differ from the reference
The problematic files are
foo.txt
bar.py
baz.rst

If you like you can add defaults and adapt the __str__() method:

>>> class UnexpectedFileContents(Exception):
...     def __init__(self, message="Some files differ from the reference", 
files=None):
...         self.message = message
...         self.files = files
...     def __str__(self):
...         s = self.message
...         if self.files is not None:
...             s = s + ": " + ", ".join(self.files)
...         return s
... 
>>> try: raise UnexpectedFileContents(files=["foo.txt", "bar.py", 
"baz.rst"])
... except UnexpectedFileContents as err: print(err)
... 
Some files differ from the reference: foo.txt, bar.py, baz.rst




More information about the Tutor mailing list