1

Is it possible to define an own with statement which automatically includes try...except error handling? For example, it would be neat to have a shorthand for this:

with Do_Something():
    try:
        ...
    except Exception as e:
        print(str(e))

...that looks like this:

with Try_Something():
    ...
    

How can we include the try...except behaviour into the following MWE class?

class Do_Something():
    def __init__(self):
        pass

    def __enter__(self):
        print('Starting...')
        # invoke "try" somewhere here?
        return(self)

    def __exit__(self, except_type, except_value, tb):
        # invoke "except" somewhere here?
Martin
  • 1,395
  • 1
  • 11
  • 33
  • The `__exit__()` methods allows exception handling. See the [docs](https://docs.python.org/3/reference/datamodel.html#object.__exit__) for details. – Klaus D. May 14 '21 at 21:34
  • Does this answer your question? [Handling exceptions inside context managers](https://stackoverflow.com/questions/35483359/handling-exceptions-inside-context-managers) – Corralien May 14 '21 at 21:38
  • @Corralien: the link was helpful, but it deals with a far more specific problem. It does not fully answer the question stated here as I do not want to handle errors in a certain way, I want to reproduce the default output of try...except. I.e., the question boils down to how to output the traceback info provided by `__exit__` in a similar way as `str(e)` would do using the argument provided by `except` . – Martin May 14 '21 at 22:54

2 Answers2

0

According to the docs, if you want to suppress exceptions, __exit__ should return True.

The args passed to __exit__ will describe the exception in case you want to make conditional decisions.

Lucas Ng
  • 671
  • 4
  • 11
0

Looks like with natively comes with try under the hood and propagets the exceptions as arguments to __exit__(...). So this could be a suitable solution:

import traceback
class Try_Something():
    def __init__(self):
        pass

    def __enter__(self):
        print('Starting...')
        # invoke "try" somewhere here? -- No, "with" automatically invokes "try"
        return(self)

    def __exit__(self, except_type, except_value, tb):
        if not except_type:
            print('finished.')
        else:
            print('failed.')
            traceback.print_exc() # prints error similar to str(e) from the question
        return(True)

I did not find a solution that goes without import traceback. Please comment if there is a way to directly print the traceback info using the provided arguments without additional modules.

Martin
  • 1,395
  • 1
  • 11
  • 33