TransWikia.com

Avoid code duplication of try/except blocks, from a class

Stack Overflow Asked by Basj on December 18, 2020

I have a class Test which is a subclass of another one (which is already a context manager, I chose nullcontext here for simplicity).

How to avoid to repeat the try/except blocks, and have this directly in the class definition?

Unlike Avoiding Multiple Try/Except blocks in Python and its answers, I’d like to do it with the class instead of creating a new function.

Example:

import contextlib

class Test(contextlib.nullcontext):
    pass

try:
    with Test('abc') as t1:
        do_something(t1)
        do_something_else()   
except ValueError:      # these exceptions are thrown from Test's parent     
    print('a')          # class/context-manager methods  (nullcontext in this example)
except KeyError:
    print('b')

try:
    with Test('def') as t2:
        do_something(t2)
        do_this(t2)
except ValueError:
    print('a')
except KeyError:
    print('b') 

TL;DR: How to move the try:, except ValueError:, except KeyError: into the class Test?

One Answer

Does putting the code in __init__ solve your problem?

import contextlib


class Test(contextlib.nullcontext):
    def __init__(self, abc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        try:
            if abc == 'def':
                raise ValueError("VALUEERROR")
            elif abc == 'ghi':
                raise KeyError("KEYERROR")
            else:
                print("OK")
        except ValueError:
            print('a')
        except KeyError:
            print('b')


x1 = Test('abc')
x2 = Test('def')
x3 = Test('ghi')

Correct answer by OctaveL on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP