Python lambda throw by abnormal clever but useless

Suppose we need a function not do anything, just throws an exception (in some systems that do the job of some handler), we can be very intuitive to write the following code:

def func():
    raise Exception("this is a exception")

It's that simple function, we hope to achieve with lambda, naturally, wrote the following code:

lambda :raise  Exception("this is a exception")

Unfortunately this is not enough ~ ~ ~ will be SyntaxError: invalid syntaxwrong. Specific reasons can see Python Lambda

The following collection practices of several available clever but useless:

method one

func = lambda: (_ for _ in ()).throw(Exception('this is an exception'))

Method Two

If you do not care what the exception information is:

func = lambda: 1/0

Understandably, this function will throw ZeroDivisionError. This approach in fact represent a class, for example, can also be written as:

func = lambda : [][0]

Such implementation is written in the back of lambda expressions will throw an exception

Method Three

Pa a very negative way, only suitable python3.x

func = lambda : exec('raise(Exception("this is an exception"))')

Method four:

Not yet read it

# python2.x
type(lambda:0)(type((lambda:0).func_code)(
  1,1,1,67,'|\0\0\202\1\0',(),(),('x',),'','',1,''),{}
)(Exception())

or

# python3.x
type(lambda: 0)(type((lambda: 0).__code__)(
    1,0,1,1,67,b'|\0\202\1\0',(),(),('x',),'','',1,b''),{}
)(Exception())

Last advice: play you can, with caution!

Reproduced in: https: //www.cnblogs.com/taceywong/p/9264963.html

Guess you like

Origin blog.csdn.net/weixin_33881050/article/details/94198035