Suppose we need a function that doesn't do anything, just throws an exception (some handler in some systems are doing it), we can write the following code intuitively:
def func(): raise Exception("this is a exception")
In this simple function, we prefer to use lambda to implement, and naturally write down the following code:
lambda :raise Exception("this is a exception")
But unfortunately this is not possible ~ ~ ~ There will be SyntaxError: invalid syntax
errors. For specific reasons, you can see Python Lambda
Here are a few of the available miracle masturbation practices:
Method One
func = lambda: (_ for _ in ()).throw(Exception('this is an exception'))
Method Two
If you don't care what the exception message is:
func = lambda: 1/0
It is not difficult to understand that this function will be thrown ZeroDivisionError
. This method actually represents a class, such as can also be written as:
func = lambda : [][0]
This type of implementation is an expression that will throw an exception after the lambda.
Method Three
A very negative way, only for python3.x.
func = lambda : exec('raise(Exception("this is an exception"))')
Method Four:
Not yet read.
# python2.xtype(lambda:0)(type((lambda:0).func_code)( 1,1,1,67,'|\0\0\202\1\0',(),(),('x',),'','',1,''),{})(Exception())
Or
# python3.xtype(lambda: 0)(type((lambda: 0).__code__)( 1,0,1,1,67,b'|\0\202\1\0',(),(),('x',),'','',1,b''),{})(Exception())
Last advice: play can, use with caution!
The miracle of Python throwing an anomaly through lambda