AnswerBun.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!

Related Questions

First negative number row in Oracle

3  Asked on November 24, 2021 by user10916118

   

how to compare hashmap in Java?

2  Asked on November 24, 2021

   

Java Functional Interfaces and Lambda Expressions

2  Asked on November 24, 2021 by vilitaria

     

How to fill array in C++?

4  Asked on November 24, 2021 by kuz

 

Using while to exit for loop

3  Asked on November 24, 2021 by lojcs

   

How to register SFML Vector2 operators with AngelScript?

2  Asked on November 24, 2021 by veridis_quo_t

     

How to make a new line in Wrap Widget

2  Asked on November 24, 2021 by hng-trnh

   

AlarmManager and BroadcastReceiver in Android Oreo+

3  Asked on November 24, 2021 by kelton-holanda-fontenele

         

HOW? Controller return nothing/current view

5  Asked on November 24, 2021 by dent-argue

 

PHP get array child

2  Asked on November 24, 2021 by tgezginis

     

How to enable/disable table column text on click

1  Asked on November 24, 2021 by asif-zaidi

       

C# Assembly.Load() method loads the wrong dll?

1  Asked on November 24, 2021 by suns-flower

         

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP