test_grammar.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 733 行 · 第 1/2 页

PY
733
字号
    finally:        msg = "continue + try/finally ok"print msg# This test warrants an explanation. It is a test specifically for SF bugs# #463359 and #462937. The bug is that a 'break' statement executed or# exception raised inside a try/except inside a loop, *after* a continue# statement has been executed in that loop, will cause the wrong number of# arguments to be popped off the stack and the instruction pointer reset to# a very small number (usually 0.) Because of this, the following test# *must* written as a function, and the tracking vars *must* be function# arguments with default values. Otherwise, the test will loop and loop.print "testing continue and break in try/except in loop"def test_break_continue_loop(extra_burning_oil = 1, count=0):    big_hippo = 2    while big_hippo:        count += 1        try:            if extra_burning_oil and big_hippo == 1:                extra_burning_oil -= 1                break            big_hippo -= 1            continue        except:            raise    if count > 2 or big_hippo <> 1:        print "continue then break in try/except in loop broken!"test_break_continue_loop()print 'return_stmt' # 'return' [testlist]def g1(): returndef g2(): return 1g1()x = g2()print 'raise_stmt' # 'raise' test [',' test]try: raise RuntimeError, 'just testing'except RuntimeError: passtry: raise KeyboardInterruptexcept KeyboardInterrupt: passprint 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*)import sysimport time, sysfrom time import timefrom sys import *from sys import path, argvprint 'global_stmt' # 'global' NAME (',' NAME)*def f():    global a    global a, b    global one, two, three, four, five, six, seven, eight, nine, tenprint 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]def f():    z = None    del z    exec 'z=1+1\n'    if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'    del z    exec 'z=1+1'    if z != 2: raise TestFailed, 'exec \'z=1+1\''    z = None    del z    import types    if hasattr(types, "UnicodeType"):        exec r"""if 1:    exec u'z=1+1\n'    if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'    del z    exec u'z=1+1'    if z != 2: raise TestFailed, 'exec u\'z=1+1\''"""f()g = {}exec 'z = 1' in gif g.has_key('__builtins__'): del g['__builtins__']if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'g = {}l = {}import warningswarnings.filterwarnings("ignore", "global statement", module="<string>")exec 'global a; a = 1; b = 2' in g, lif g.has_key('__builtins__'): del g['__builtins__']if l.has_key('__builtins__'): del l['__builtins__']if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)print "assert_stmt" # assert_stmt: 'assert' test [',' test]assert 1assert 1, 1assert lambda x:xassert 1, lambda x:x+1### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef# Tested belowprint 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]if 1: passif 1: passelse: passif 0: passelif 0: passif 0: passelif 0: passelif 0: passelif 0: passelse: passprint 'while_stmt' # 'while' test ':' suite ['else' ':' suite]while 0: passwhile 0: passelse: passprint 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]for i in 1, 2, 3: passfor i, j, k in (): passelse: passclass Squares:    def __init__(self, max):        self.max = max        self.sofar = []    def __len__(self): return len(self.sofar)    def __getitem__(self, i):        if not 0 <= i < self.max: raise IndexError        n = len(self.sofar)        while n <= i:            self.sofar.append(n*n)            n = n+1        return self.sofar[i]n = 0for x in Squares(10): n = n+xif n != 285: raise TestFailed, 'for over growing sequence'print 'try_stmt'### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]###         | 'try' ':' suite 'finally' ':' suite### except_clause: 'except' [expr [',' expr]]try:    1/0except ZeroDivisionError:    passelse:    passtry: 1/0except EOFError: passexcept TypeError, msg: passexcept RuntimeError, msg: passexcept: passelse: passtry: 1/0except (EOFError, TypeError, ZeroDivisionError): passtry: 1/0except (EOFError, TypeError, ZeroDivisionError), msg: passtry: passfinally: passprint 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENTif 1: passif 1:    passif 1:    #    #    #    pass    pass    #    pass    #print 'test'### and_test ('or' and_test)*### and_test: not_test ('and' not_test)*### not_test: 'not' not_test | comparisonif not 1: passif 1 and 1: passif 1 or 1: passif not not not 1: passif not 1 and 1 and 1: passif 1 and 1 or 1 and 1 and 1 or not 1 and 1: passprint 'comparison'### comparison: expr (comp_op expr)*### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'if 1: passx = (1 == 1)if 1 == 1: passif 1 != 1: passif 1 <> 1: passif 1 < 1: passif 1 > 1: passif 1 <= 1: passif 1 >= 1: passif 1 is 1: passif 1 is not 1: passif 1 in (): passif 1 not in (): passif 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: passprint 'binary mask ops'x = 1 & 1x = 1 ^ 1x = 1 | 1print 'shift ops'x = 1 << 1x = 1 >> 1x = 1 << 1 >> 1print 'additive ops'x = 1x = 1 + 1x = 1 - 1 - 1x = 1 - 1 + 1 - 1 + 1print 'multiplicative ops'x = 1 * 1x = 1 / 1x = 1 % 1x = 1 / 1 * 1 % 1print 'unary ops'x = +1x = -1x = ~1x = ~1 ^ 1 & 1 | 1 & 1 ^ -1x = -1*1/1 + 1*1 - ---1*1print 'selectors'### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME### subscript: expr | [expr] ':' [expr]f1()f2(1)f2(1,)f3(1, 2)f3(1, 2,)f4(1, (2, (3, 4)))v0()v0(1)v0(1,)v0(1,2)v0(1,2,3,4,5,6,7,8,9,0)v1(1)v1(1,)v1(1,2)v1(1,2,3)v1(1,2,3,4,5,6,7,8,9,0)v2(1,2)v2(1,2,3)v2(1,2,3,4)v2(1,2,3,4,5,6,7,8,9,0)v3(1,(2,3))v3(1,(2,3),4)v3(1,(2,3),4,5,6,7,8,9,0)printimport sys, timec = sys.path[0]x = time.time()x = sys.modules['time'].time()a = '01234'c = a[0]c = a[-1]s = a[0:5]s = a[:5]s = a[0:]s = a[:]s = a[-5:]s = a[:-1]s = a[-4:-3]print 'atoms'### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING### dictmaker: test ':' test (',' test ':' test)* [',']x = (1)x = (1 or 2 or 3)x = (1 or 2 or 3, 2, 3)x = []x = [1]x = [1 or 2 or 3]x = [1 or 2 or 3, 2, 3]x = []x = {}x = {'one': 1}x = {'one': 1,}x = {'one' or 'two': 1 or 2}x = {'one': 1, 'two': 2}x = {'one': 1, 'two': 2,}x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}x = `x`x = `1 or 2 or 3`x = xx = 'x'x = 123### exprlist: expr (',' expr)* [',']### testlist: test (',' test)* [',']# These have been exercised enough aboveprint 'classdef' # 'class' NAME ['(' testlist ')'] ':' suiteclass B: passclass C1(B): passclass C2(B): passclass D(C1, C2, B): passclass C:    def meth1(self): pass    def meth2(self, arg): pass    def meth3(self, a1, a2): pass# list comprehension testsnums = [1, 2, 3, 4, 5]strs = ["Apple", "Banana", "Coconut"]spcs = ["  Apple", " Banana ", "Coco  nut  "]print [s.strip() for s in spcs]print [3 * x for x in nums]print [x for x in nums if x > 2]print [(i, s) for i in nums for s in strs]print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)] def test_in_func(l):    return [None < x < 3 for x in l if x > 2]print test_in_func(nums)def test_nested_front():    print [[y for y in [x, x + 1]] for x in [1,3,5]]test_nested_front()check_syntax("[i, s for i in nums for s in strs]")check_syntax("[x if y]")suppliers = [  (1, "Boeing"),  (2, "Ford"),  (3, "Macdonalds")]parts = [  (10, "Airliner"),  (20, "Engine"),  (30, "Cheeseburger")]suppart = [  (1, 10), (1, 20), (2, 20), (3, 30)]print [  (sname, pname)    for (sno, sname) in suppliers      for (pno, pname) in parts        for (sp_sno, sp_pno) in suppart          if sno == sp_sno and pno == sp_pno]

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?