Is it possible to declare an abstract exception in Python?

I would like to declare a hierarchy of custom exceptions in Python. However, I would like my top-level custom class ( TransactionException ) to be abstract. That is, I intend TransactionException to specify the methods that should be defined by its subclasses. However, a TransactionException should never be thrown or thrown.

I have the following code:

 from abc import ABCMeta, abstractmethod class TransactionException(Exception): __metaclass__ = ABCMeta @abstractmethod def displayErrorMessage(self): pass 

However, the above code allows me to create an instance of TransactionException ...

 a = TransactionException() 

In this case, a does not make sense, and an exception should be made instead. The following code eliminates the fact that TransactionException is a subclass of Exception ...

 from abc import ABCMeta, abstractmethod class TransactionException(): __metaclass__ = ABCMeta @abstractmethod def displayErrorMessage(self): pass 

This code correctly prohibits instantiation, but now I cannot raise a subclass of TransactionException because it is no longer an Exception .

Is it possible to define an abstract exception in Python? If so, how? If not, why not?

NOTE. I am using Python 2.7, but would happily agree to respond to Python 2.x or Python 3.x.

+4
source share
2 answers

There's a great answer on this topic from Alex Martelli here . In essence, this is due to the way those initializer elements ( __init__ ) of the various base classes ( object , list , and, I suppose, Exception ) behave.

When an abstract class inherits from object (which is the default if no other base class is specified), the __init__ method is set as the object method, which performs a heavy lift in checking if all abstract methods have been implemented.

If an abstract class inherits from another base class, it will receive this __init__ class method. Other classes, such as list and Exception , do not seem to check the implementation of the abstract method , so their creation is allowed.

Another answer offers a suggested solution for this. Of course, the other option you have is to simply admit that the abstract class will be realistic and try to dissuade it.

+2
source
 class TransactionException(Exception): def __init__(self, *args, **kwargs): raise NotImplementedError('you should not be raising this') class EverythingLostException(TransactionException): def __init__(self, msg): super(TransactionException, self).__init__(msg) try: raise EverythingLostException('we are doomed!') except TransactionException: print 'check' try: raise TransactionException('we are doomed!') except TransactionException: print 'oops' 
+4
source

Source: https://habr.com/ru/post/972359/


All Articles