Python assert: Automatically generate error messages

Source: Internet
Author: User

Friends who have used python assert should often encounter such doubts, such as:

(A, b) = (1, ' 1 ')

Assert A==b # Error:assertionerror

When debugging code, it's hard to see why it's wrong, unless it's written like this:

Assert 1== ' 1 ', "fact==expect, [fact]=%s, [expect]=%s"% ([a],[b]) # assertionerror:fact==expect, [fact]=[1], [expect] =[' 1 ']

But so every time to write the error message, used frequently will be a bit cumbersome, this article introduces a "dynamic assertion" mechanism, such as:

assertx (' 1 ', "= =", 1) # (%s[' f '] = =%s[' e ']), [fact]=[' 1 '], [expe]=[1]

The code is as follows:

1 #Encoding=utf-82 defassertx (fact, expr, expe):3     """#原有的assert看不到表达式内部, and cannot generate error messages automatically4 if __name__== ' __main__ ':5 assertx (1, "! =", 2)6 assertx (1, "%s[' F '] in%s[' e ']", [1,11])7 Assertx ([1,100], "%s[' e '] in%s[' F ']", +)8 Try:9 assertx (' 1 ', "= =", 1)Ten except Standarderror,e: One Print E # (%s[' f '] = =%s[' e ']), [fact]=[' 1 '], [expe]=[1] A      - Try: - assertx (' 1 ', "not in", [' 1 ']) the except Standarderror,e: - Print E # when typesimple, Assert:expr.find (") ==-1, [expr]=[' not in '] -     """ -FDc = {'F': Fact} +EDc = {'e': Expe} -Atfact = Expr.find ("%s[' F ']") +Atexpe = Expr.find ("%s[' e ']") A     if(atfact>-1 andATEXPE&GT;-1):#"Type=custom" atExprstr =Expr -         ifAtfact <Atexpe: -Exprformat = expr%(FDC,EDC) -         Else: -Exprformat = expr%(EDC,FDC) -     Else:#"Type=simple" in         assertExpr.find (' ') ==-1,  -                 "When typesimple, Assert:expr.find (') ==-1, [expr]=%s"%[expr] toExprstr ="(%%s[' F ']%s%%s[' e '])"% expr#exam: ' (%s[' f '] = =%s[' e ']) ' +Exprformat = exprstr% (FDC,EDC)#exam: ' ("factvalue" = = "Expevalue") ' -     if  notEval (Exprformat):#exam: "'%s ' = = '%s '" the         RaiseStandardError ("""%s, [fact]=%s, [expe]=%s"""% (Exprstr,[fact],[expe]))

Python assert: Automatically generate error messages

Related Article

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.