Is it possible to raise an exception in Python without using raise
statement?
For example, instead of raise ValueError
use some method like ValueError.raise()
. This question only relates to python built-in exceptions and not some custom exception classes that can be build from them.
Define a helper function to raise the exception:
def raising(exc: BaseException):
raise exc
This can then be used in any place an expression can be used, such as lambda
or assignment expressions.
This approach can be used to make practically any statement usable as an expression. However, be mindful that statements are an important part of code readability - when in doubt, prefer to refractor the code so that the statement can be used in place.