~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Quick Python: Refactoring Exceptions with Context Manager

Published on

I generally find exception syntax a little clunky…

try:
    for _ in range(5):
        sleep(1)
except KeyboardInterrupt:
    # Awesome task 1
    # Awesome task 2...
    pass

Especially if you end up capturing the same exceptions and handling it the same way.

try:
    for _ in range(5):
        sleep(1)
except KeyboardInterrupt:
    # Awesome task 1
    # Awesome task 2...
    pass

try:
    for _ in range(2):
        sleep(1)
except KeyboardInterrupt:
    # Awesome task 1
    # Awesome task 2...
    pass

One way to make our code more DRY (don’t-repeat-yourself) is to make use of Python’s context managers.

@contextmanager
def handle_sigint():
    try:
        yield
    except KeyboardInterrupt:
        # Awesome task 1
        # Awesome task 2...
        pass

Using the context manager, everything within the indented block gets executed within the try block.

with handle_sigint():
    for _ in range(5):
        sleep(1)

with handle_sigint():
    for _ in range(2):
        sleep(1)

In fact, we can write this in a generic way to give us an alternative syntax for handling exceptions.

@contextmanager
def handle_exception(f, *exceptions):
    try:
        yield
    except exceptions as e:
        f(e)

For example, let’s tell the user that we’re explicitly ignoring their exception

def ignore(e):
    print("Ignoring", e.__class__.__name__)

with handle_exception(ignore, NotImplementedError, KeyboardInterrupt):
    for _ in range(5):
        sleep(1)
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :