Python: can I overload the raise statement with __raise __ (self) :?

Here is my exception class that uses raise :

class SCE(Exception):
    """
    An error while performing SCE functions.
    """
    def __init__(self, value=None):
        """
        Message: A string message or an iterable of strings.
        """
        if value is None:
            self._values = []
        elif isinstance(value, str):
            self._values = [value]
        else:
            self._values = list(value)

    def __raise__(self):
        print('raising')
        if not len(self._values):
            return

    def __str__(self):
        return self.__repr__()

    def __iter__(self):
        return iter(self._values)

    def __repr__(self):
        return repr(self._values)

Currently, if I throw this exception without a value, I get a trace followed by:

__main__.SCE: []

Instead of what I expected was:

raising
>>>

How do you overload raise?

+4
source share
3 answers

, __raise__. 2004 comp.lang.python, - , , . , , - , - -, raise.

+3

__raise__ ( , , , , Python).

? - , , ( , , __init__ , except). , Python ?

+1

Like __raise__others, such a closed method __raise__. Nothing prevents one from being identified. For example:

#!/usr/bin/env python3


class MyClass(object):
    def __init__(self, raise_exceptions=False):
        self.raise_exceptions = raise_exceptions

    def __raise__(self, err=None):
        print(err, flush=True)
        if self.raise_exceptions:
            raise err

    def run(self):
        try:
            assert False, 'assertion False'
        except Exception as err:
            self.__raise__(err)


if __name__ == '__main__':
    MyClass(raise_exceptions=False).run()
    MyClass(raise_exceptions=True).run()

Here is the conclusion:

$ python3 my_class.py
assertion False
assertion False
Traceback (most recent call last):
  File "my_class.py", line 22, in <module>
    MyClass(raise_exceptions=True).run()
  File "my_class.py", line 17, in run
    self.__raise__(err)
  File "my_class.py", line 11, in __raise__
    raise err
  File "my_class.py", line 15, in run
    assert False, 'assertion False'
AssertionError: assertion False

Process finished with exit code 1
0
source

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


All Articles