The miracle of Python throwing an anomaly through lambda

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.