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>-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