Best Python code snippet using hypothesis
test_sys_settrace.py
Source:test_sys_settrace.py  
...569class JumpTestCase(unittest.TestCase):570    def setUp(self):571        self.addCleanup(sys.settrace, sys.gettrace())572        sys.settrace(None)573    def compare_jump_output(self, expected, received):574        if received != expected:575            self.fail( "Outputs don't match:\n" +576                       "Expected: " + repr(expected) + "\n" +577                       "Received: " + repr(received))578    def run_test(self, func, jumpFrom, jumpTo, expected, error=None,579                 event='line', decorated=False):580        tracer = JumpTracer(func, jumpFrom, jumpTo, event, decorated)581        sys.settrace(tracer.trace)582        output = []583        if error is None:584            func(output)585        else:586            with self.assertRaisesRegex(*error):587                func(output)588        sys.settrace(None)589        self.compare_jump_output(expected, output)590    def run_async_test(self, func, jumpFrom, jumpTo, expected, error=None,591                 event='line', decorated=False):592        tracer = JumpTracer(func, jumpFrom, jumpTo, event, decorated)593        sys.settrace(tracer.trace)594        output = []595        if error is None:596            asyncio.run(func(output))597        else:598            with self.assertRaisesRegex(*error):599                asyncio.run(func(output))600        sys.settrace(None)601        asyncio.set_event_loop_policy(None)602        self.compare_jump_output(expected, output)603    def jump_test(jumpFrom, jumpTo, expected, error=None, event='line'):604        """Decorator that creates a test that makes a jump605        from one place to another in the following code.606        """607        def decorator(func):608            @wraps(func)609            def test(self):610                self.run_test(func, jumpFrom, jumpTo, expected,611                              error=error, event=event, decorated=True)612            return test613        return decorator614    def async_jump_test(jumpFrom, jumpTo, expected, error=None, event='line'):615        """Decorator that creates a test that makes a jump616        from one place to another in the following asynchronous code.617        """618        def decorator(func):619            @wraps(func)620            def test(self):621                self.run_async_test(func, jumpFrom, jumpTo, expected,622                              error=error, event=event, decorated=True)623            return test624        return decorator625    ## The first set of 'jump' tests are for things that are allowed:626    @jump_test(1, 3, [3])627    def test_jump_simple_forwards(output):628        output.append(1)629        output.append(2)630        output.append(3)631    @jump_test(2, 1, [1, 1, 2])632    def test_jump_simple_backwards(output):633        output.append(1)634        output.append(2)635    @jump_test(3, 5, [2, 5])636    def test_jump_out_of_block_forwards(output):637        for i in 1, 2:638            output.append(2)639            for j in [3]:  # Also tests jumping over a block640                output.append(4)641        output.append(5)642    @jump_test(6, 1, [1, 3, 5, 1, 3, 5, 6, 7])643    def test_jump_out_of_block_backwards(output):644        output.append(1)645        for i in [1]:646            output.append(3)647            for j in [2]:  # Also tests jumping over a block648                output.append(5)649            output.append(6)650        output.append(7)651    @async_jump_test(4, 5, [3, 5])652    async def test_jump_out_of_async_for_block_forwards(output):653        for i in [1]:654            async for i in asynciter([1, 2]):655                output.append(3)656                output.append(4)657            output.append(5)658    @async_jump_test(5, 2, [2, 4, 2, 4, 5, 6])659    async def test_jump_out_of_async_for_block_backwards(output):660        for i in [1]:661            output.append(2)662            async for i in asynciter([1]):663                output.append(4)664                output.append(5)665            output.append(6)666    @jump_test(1, 2, [3])667    def test_jump_to_codeless_line(output):668        output.append(1)669        # Jumping to this line should skip to the next one.670        output.append(3)671    @jump_test(2, 2, [1, 2, 3])672    def test_jump_to_same_line(output):673        output.append(1)674        output.append(2)675        output.append(3)676    # Tests jumping within a finally block, and over one.677    @jump_test(4, 9, [2, 9])678    def test_jump_in_nested_finally(output):679        try:680            output.append(2)681        finally:682            output.append(4)683            try:684                output.append(6)685            finally:686                output.append(8)687            output.append(9)688    @jump_test(6, 7, [2, 7], (ZeroDivisionError, ''))689    def test_jump_in_nested_finally_2(output):690        try:691            output.append(2)692            1/0693            return694        finally:695            output.append(6)696            output.append(7)697        output.append(8)698    @jump_test(6, 11, [2, 11], (ZeroDivisionError, ''))699    def test_jump_in_nested_finally_3(output):700        try:701            output.append(2)702            1/0703            return704        finally:705            output.append(6)706            try:707                output.append(8)708            finally:709                output.append(10)710            output.append(11)711        output.append(12)712    @jump_test(5, 11, [2, 4, 12])713    def test_jump_over_return_try_finally_in_finally_block(output):714        try:715            output.append(2)716        finally:717            output.append(4)718            output.append(5)719            return720            try:721                output.append(8)722            finally:723                output.append(10)724            pass725        output.append(12)726    @jump_test(3, 4, [1, 4])727    def test_jump_infinite_while_loop(output):728        output.append(1)729        while True:730            output.append(3)731        output.append(4)732    @jump_test(2, 4, [4, 4])733    def test_jump_forwards_into_while_block(output):734        i = 1735        output.append(2)736        while i <= 2:737            output.append(4)738            i += 1739    @jump_test(5, 3, [3, 3, 3, 5])740    def test_jump_backwards_into_while_block(output):741        i = 1742        while i <= 2:743            output.append(3)744            i += 1745        output.append(5)746    @jump_test(2, 3, [1, 3])747    def test_jump_forwards_out_of_with_block(output):748        with tracecontext(output, 1):749            output.append(2)750        output.append(3)751    @async_jump_test(2, 3, [1, 3])752    async def test_jump_forwards_out_of_async_with_block(output):753        async with asynctracecontext(output, 1):754            output.append(2)755        output.append(3)756    @jump_test(3, 1, [1, 2, 1, 2, 3, -2])757    def test_jump_backwards_out_of_with_block(output):758        output.append(1)759        with tracecontext(output, 2):760            output.append(3)761    @async_jump_test(3, 1, [1, 2, 1, 2, 3, -2])762    async def test_jump_backwards_out_of_async_with_block(output):763        output.append(1)764        async with asynctracecontext(output, 2):765            output.append(3)766    @jump_test(2, 5, [5])767    def test_jump_forwards_out_of_try_finally_block(output):768        try:769            output.append(2)770        finally:771            output.append(4)772        output.append(5)773    @jump_test(3, 1, [1, 1, 3, 5])774    def test_jump_backwards_out_of_try_finally_block(output):775        output.append(1)776        try:777            output.append(3)778        finally:779            output.append(5)780    @jump_test(2, 6, [6])781    def test_jump_forwards_out_of_try_except_block(output):782        try:783            output.append(2)784        except:785            output.append(4)786            raise787        output.append(6)788    @jump_test(3, 1, [1, 1, 3])789    def test_jump_backwards_out_of_try_except_block(output):790        output.append(1)791        try:792            output.append(3)793        except:794            output.append(5)795            raise796    @jump_test(5, 7, [4, 7, 8])797    def test_jump_between_except_blocks(output):798        try:799            1/0800        except ZeroDivisionError:801            output.append(4)802            output.append(5)803        except FloatingPointError:804            output.append(7)805        output.append(8)806    @jump_test(5, 6, [4, 6, 7])807    def test_jump_within_except_block(output):808        try:809            1/0810        except:811            output.append(4)812            output.append(5)813            output.append(6)814        output.append(7)815    @jump_test(2, 4, [1, 4, 5, -4])816    def test_jump_across_with(output):817        output.append(1)818        with tracecontext(output, 2):819            output.append(3)820        with tracecontext(output, 4):821            output.append(5)822    @async_jump_test(2, 4, [1, 4, 5, -4])823    async def test_jump_across_async_with(output):824        output.append(1)825        async with asynctracecontext(output, 2):826            output.append(3)827        async with asynctracecontext(output, 4):828            output.append(5)829    @jump_test(4, 5, [1, 3, 5, 6])830    def test_jump_out_of_with_block_within_for_block(output):831        output.append(1)832        for i in [1]:833            with tracecontext(output, 3):834                output.append(4)835            output.append(5)836        output.append(6)837    @async_jump_test(4, 5, [1, 3, 5, 6])838    async def test_jump_out_of_async_with_block_within_for_block(output):839        output.append(1)840        for i in [1]:841            async with asynctracecontext(output, 3):842                output.append(4)843            output.append(5)844        output.append(6)845    @jump_test(4, 5, [1, 2, 3, 5, -2, 6])846    def test_jump_out_of_with_block_within_with_block(output):847        output.append(1)848        with tracecontext(output, 2):849            with tracecontext(output, 3):850                output.append(4)851            output.append(5)852        output.append(6)853    @async_jump_test(4, 5, [1, 2, 3, 5, -2, 6])854    async def test_jump_out_of_async_with_block_within_with_block(output):855        output.append(1)856        with tracecontext(output, 2):857            async with asynctracecontext(output, 3):858                output.append(4)859            output.append(5)860        output.append(6)861    @jump_test(5, 6, [2, 4, 6, 7])862    def test_jump_out_of_with_block_within_finally_block(output):863        try:864            output.append(2)865        finally:866            with tracecontext(output, 4):867                output.append(5)868            output.append(6)869        output.append(7)870    @async_jump_test(5, 6, [2, 4, 6, 7])871    async def test_jump_out_of_async_with_block_within_finally_block(output):872        try:873            output.append(2)874        finally:875            async with asynctracecontext(output, 4):876                output.append(5)877            output.append(6)878        output.append(7)879    @jump_test(8, 11, [1, 3, 5, 11, 12])880    def test_jump_out_of_complex_nested_blocks(output):881        output.append(1)882        for i in [1]:883            output.append(3)884            for j in [1, 2]:885                output.append(5)886                try:887                    for k in [1, 2]:888                        output.append(8)889                finally:890                    output.append(10)891            output.append(11)892        output.append(12)893    @jump_test(3, 5, [1, 2, 5])894    def test_jump_out_of_with_assignment(output):895        output.append(1)896        with tracecontext(output, 2) \897                as x:898            output.append(4)899        output.append(5)900    @async_jump_test(3, 5, [1, 2, 5])901    async def test_jump_out_of_async_with_assignment(output):902        output.append(1)903        async with asynctracecontext(output, 2) \904                as x:905            output.append(4)906        output.append(5)907    @jump_test(3, 6, [1, 6, 8, 9])908    def test_jump_over_return_in_try_finally_block(output):909        output.append(1)910        try:911            output.append(3)912            if not output: # always false913                return914            output.append(6)915        finally:916            output.append(8)917        output.append(9)918    @jump_test(5, 8, [1, 3, 8, 10, 11, 13])919    def test_jump_over_break_in_try_finally_block(output):920        output.append(1)921        while True:922            output.append(3)923            try:924                output.append(5)925                if not output: # always false926                    break927                output.append(8)928            finally:929                output.append(10)930            output.append(11)931            break932        output.append(13)933    @jump_test(1, 7, [7, 8])934    def test_jump_over_for_block_before_else(output):935        output.append(1)936        if not output:  # always false937            for i in [3]:938                output.append(4)939        else:940            output.append(6)941            output.append(7)942        output.append(8)943    @async_jump_test(1, 7, [7, 8])944    async def test_jump_over_async_for_block_before_else(output):945        output.append(1)946        if not output:  # always false947            async for i in asynciter([3]):948                output.append(4)949        else:950            output.append(6)951            output.append(7)952        output.append(8)953    # The second set of 'jump' tests are for things that are not allowed:954    @jump_test(2, 3, [1], (ValueError, 'after'))955    def test_no_jump_too_far_forwards(output):956        output.append(1)957        output.append(2)958    @jump_test(2, -2, [1], (ValueError, 'before'))959    def test_no_jump_too_far_backwards(output):960        output.append(1)961        output.append(2)962    # Test each kind of 'except' line.963    @jump_test(2, 3, [4], (ValueError, 'except'))964    def test_no_jump_to_except_1(output):965        try:966            output.append(2)967        except:968            output.append(4)969            raise970    @jump_test(2, 3, [4], (ValueError, 'except'))971    def test_no_jump_to_except_2(output):972        try:973            output.append(2)974        except ValueError:975            output.append(4)976            raise977    @jump_test(2, 3, [4], (ValueError, 'except'))978    def test_no_jump_to_except_3(output):979        try:980            output.append(2)981        except ValueError as e:982            output.append(4)983            raise e984    @jump_test(2, 3, [4], (ValueError, 'except'))985    def test_no_jump_to_except_4(output):986        try:987            output.append(2)988        except (ValueError, RuntimeError) as e:989            output.append(4)990            raise e991    @jump_test(1, 3, [], (ValueError, 'into'))992    def test_no_jump_forwards_into_for_block(output):993        output.append(1)994        for i in 1, 2:995            output.append(3)996    @async_jump_test(1, 3, [], (ValueError, 'into'))997    async def test_no_jump_forwards_into_async_for_block(output):998        output.append(1)999        async for i in asynciter([1, 2]):1000            output.append(3)1001    @jump_test(3, 2, [2, 2], (ValueError, 'into'))1002    def test_no_jump_backwards_into_for_block(output):1003        for i in 1, 2:1004            output.append(2)1005        output.append(3)1006    @async_jump_test(3, 2, [2, 2], (ValueError, 'into'))1007    async def test_no_jump_backwards_into_async_for_block(output):1008        async for i in asynciter([1, 2]):1009            output.append(2)1010        output.append(3)1011    @jump_test(1, 3, [], (ValueError, 'into'))1012    def test_no_jump_forwards_into_with_block(output):1013        output.append(1)1014        with tracecontext(output, 2):1015            output.append(3)1016    @async_jump_test(1, 3, [], (ValueError, 'into'))1017    async def test_no_jump_forwards_into_async_with_block(output):1018        output.append(1)1019        async with asynctracecontext(output, 2):1020            output.append(3)1021    @jump_test(3, 2, [1, 2, -1], (ValueError, 'into'))1022    def test_no_jump_backwards_into_with_block(output):1023        with tracecontext(output, 1):1024            output.append(2)1025        output.append(3)1026    @async_jump_test(3, 2, [1, 2, -1], (ValueError, 'into'))1027    async def test_no_jump_backwards_into_async_with_block(output):1028        async with asynctracecontext(output, 1):1029            output.append(2)1030        output.append(3)1031    @jump_test(1, 3, [], (ValueError, 'into'))1032    def test_no_jump_forwards_into_try_finally_block(output):1033        output.append(1)1034        try:1035            output.append(3)1036        finally:1037            output.append(5)1038    @jump_test(5, 2, [2, 4], (ValueError, 'into'))1039    def test_no_jump_backwards_into_try_finally_block(output):1040        try:1041            output.append(2)1042        finally:1043            output.append(4)1044        output.append(5)1045    @jump_test(1, 3, [], (ValueError, 'into'))1046    def test_no_jump_forwards_into_try_except_block(output):1047        output.append(1)1048        try:1049            output.append(3)1050        except:1051            output.append(5)1052            raise1053    @jump_test(6, 2, [2], (ValueError, 'into'))1054    def test_no_jump_backwards_into_try_except_block(output):1055        try:1056            output.append(2)1057        except:1058            output.append(4)1059            raise1060        output.append(6)1061    # 'except' with a variable creates an implicit finally block1062    @jump_test(5, 7, [4], (ValueError, 'into'))1063    def test_no_jump_between_except_blocks_2(output):1064        try:1065            1/01066        except ZeroDivisionError:1067            output.append(4)1068            output.append(5)1069        except FloatingPointError as e:1070            output.append(7)1071        output.append(8)1072    @jump_test(1, 5, [], (ValueError, "into a 'finally'"))1073    def test_no_jump_into_finally_block(output):1074        output.append(1)1075        try:1076            output.append(3)1077        finally:1078            output.append(5)1079    @jump_test(3, 6, [2, 5, 6], (ValueError, "into a 'finally'"))1080    def test_no_jump_into_finally_block_from_try_block(output):1081        try:1082            output.append(2)1083            output.append(3)1084        finally:  # still executed if the jump is failed1085            output.append(5)1086            output.append(6)1087        output.append(7)1088    @jump_test(5, 1, [1, 3], (ValueError, "out of a 'finally'"))1089    def test_no_jump_out_of_finally_block(output):1090        output.append(1)1091        try:1092            output.append(3)1093        finally:1094            output.append(5)1095    @jump_test(1, 5, [], (ValueError, "into an 'except'"))1096    def test_no_jump_into_bare_except_block(output):1097        output.append(1)1098        try:1099            output.append(3)1100        except:1101            output.append(5)1102    @jump_test(1, 5, [], (ValueError, "into an 'except'"))1103    def test_no_jump_into_qualified_except_block(output):1104        output.append(1)1105        try:1106            output.append(3)1107        except Exception:1108            output.append(5)1109    @jump_test(3, 6, [2, 5, 6], (ValueError, "into an 'except'"))1110    def test_no_jump_into_bare_except_block_from_try_block(output):1111        try:1112            output.append(2)1113            output.append(3)1114        except:  # executed if the jump is failed1115            output.append(5)1116            output.append(6)1117            raise1118        output.append(8)1119    @jump_test(3, 6, [2], (ValueError, "into an 'except'"))1120    def test_no_jump_into_qualified_except_block_from_try_block(output):1121        try:1122            output.append(2)1123            output.append(3)1124        except ZeroDivisionError:1125            output.append(5)1126            output.append(6)1127            raise1128        output.append(8)1129    @jump_test(7, 1, [1, 3, 6], (ValueError, "out of an 'except'"))1130    def test_no_jump_out_of_bare_except_block(output):1131        output.append(1)1132        try:1133            output.append(3)1134            1/01135        except:1136            output.append(6)1137            output.append(7)1138    @jump_test(7, 1, [1, 3, 6], (ValueError, "out of an 'except'"))1139    def test_no_jump_out_of_qualified_except_block(output):1140        output.append(1)1141        try:1142            output.append(3)1143            1/01144        except Exception:1145            output.append(6)1146            output.append(7)1147    @jump_test(3, 5, [1, 2, -2], (ValueError, 'into'))1148    def test_no_jump_between_with_blocks(output):1149        output.append(1)1150        with tracecontext(output, 2):1151            output.append(3)1152        with tracecontext(output, 4):1153            output.append(5)1154    @async_jump_test(3, 5, [1, 2, -2], (ValueError, 'into'))1155    async def test_no_jump_between_async_with_blocks(output):1156        output.append(1)1157        async with asynctracecontext(output, 2):1158            output.append(3)1159        async with asynctracecontext(output, 4):1160            output.append(5)1161    @jump_test(5, 7, [2, 4], (ValueError, 'finally'))1162    def test_no_jump_over_return_out_of_finally_block(output):1163        try:1164            output.append(2)1165        finally:1166            output.append(4)1167            output.append(5)1168            return1169        output.append(7)1170    @jump_test(7, 4, [1, 6], (ValueError, 'into'))1171    def test_no_jump_into_for_block_before_else(output):1172        output.append(1)1173        if not output:  # always false1174            for i in [3]:1175                output.append(4)1176        else:1177            output.append(6)1178            output.append(7)1179        output.append(8)1180    @async_jump_test(7, 4, [1, 6], (ValueError, 'into'))1181    async def test_no_jump_into_async_for_block_before_else(output):1182        output.append(1)1183        if not output:  # always false1184            async for i in asynciter([3]):1185                output.append(4)1186        else:1187            output.append(6)1188            output.append(7)1189        output.append(8)1190    def test_no_jump_to_non_integers(self):1191        self.run_test(no_jump_to_non_integers, 2, "Spam", [True])1192    def test_no_jump_without_trace_function(self):1193        # Must set sys.settrace(None) in setUp(), else condition is not1194        # triggered.1195        no_jump_without_trace_function()1196    def test_large_function(self):1197        d = {}1198        exec("""def f(output):        # line 01199            x = 0                     # line 11200            y = 1                     # line 21201            '''                       # line 31202            %s                        # lines 4-10041203            '''                       # line 10051204            x += 1                    # line 10061205            output.append(x)          # line 10071206            return""" % ('\n' * 1000,), d)1207        f = d['f']1208        self.run_test(f, 2, 1007, [0])1209    def test_jump_to_firstlineno(self):1210        # This tests that PDB can jump back to the first line in a1211        # file.  See issue #1689458.  It can only be triggered in a1212        # function call if the function is defined on a single line.1213        code = compile("""1214# Comments don't count.1215output.append(2)  # firstlineno is here.1216output.append(3)1217output.append(4)1218""", "<fake module>", "exec")1219        class fake_function:1220            __code__ = code1221        tracer = JumpTracer(fake_function, 2, 0)1222        sys.settrace(tracer.trace)1223        namespace = {"output": []}1224        exec(code, namespace)1225        sys.settrace(None)1226        self.compare_jump_output([2, 3, 2, 3, 4], namespace["output"])1227    @jump_test(2, 3, [1], event='call', error=(ValueError, "can't jump from"1228               " the 'call' trace event of a new frame"))1229    def test_no_jump_from_call(output):1230        output.append(1)1231        def nested():1232            output.append(3)1233        nested()1234        output.append(5)1235    @jump_test(2, 1, [1], event='return', error=(ValueError,1236               "can only jump from a 'line' trace event"))1237    def test_no_jump_from_return_event(output):1238        output.append(1)1239        return1240    @jump_test(2, 1, [1], event='exception', error=(ValueError,...Record.py
Source:Record.py  
1"""Hold GenBank data in a straightforward format.2classes:3o Record - All of the information in a GenBank record.4o Reference - hold reference data for a record.5o Feature - Hold the information in a Feature Table.6o Qualifier - Qualifiers on a Feature.717-MAR-2009: added support for WGS and WGS_SCAFLD lines.  Ying Huang & Iddo Friedberg8"""9# local stuff10import Bio.GenBank11def _wrapped_genbank(information, indent, wrap_space = 1, split_char = " "):12    """Write a line of GenBank info that can wrap over multiple lines.13    This takes a line of information which can potentially wrap over14    multiple lines, and breaks it up with carriage returns and15    indentation so it fits properly into a GenBank record.16    Arguments:17    o information - The string holding the information we want18    wrapped in GenBank method.19    o indent - The indentation on the lines we are writing.20    o wrap_space - Whether or not to wrap only on spaces in the21    information.22    o split_char - A specific character to split the lines on. By default23    spaces are used.24    """25    info_length = Record.GB_LINE_LENGTH - indent26    if not information:27        #GenBank files use "." for missing data28        return ".\n"29    if wrap_space:30        info_parts = information.split(split_char)31    else:32        cur_pos = 033        info_parts = []34        while cur_pos < len(information):35            info_parts.append(information[cur_pos: cur_pos + info_length])36            cur_pos += info_length37            38    # first get the information string split up by line39    output_parts = []40    cur_part = ""41    for info_part in info_parts:42        if len(cur_part) + 1 + len(info_part) > info_length:43            if cur_part:44                if split_char != " ":45                    cur_part += split_char46                output_parts.append(cur_part)47            cur_part = info_part48        else:49            if cur_part == "":50                cur_part = info_part51            else:52                cur_part += split_char + info_part53    # add the last bit of information to the output54    if cur_part:55        output_parts.append(cur_part)56    # now format the information string for return57    output_info = output_parts[0] + "\n"58    for output_part in output_parts[1:]:59        output_info += " " * indent + output_part + "\n"60    return output_info            61        62def _indent_genbank(information, indent):63    """Write out information with the specified indent.64    Unlike _wrapped_genbank, this function makes no attempt to wrap65    lines -- it assumes that the information already has newlines in the66    appropriate places, and will add the specified indent to the start of67    each line.68    """69    # split the info into lines based on line breaks70    info_parts = information.split("\n")71    # the first line will have no indent72    output_info = info_parts[0] + "\n"73    for info_part in info_parts[1:]:74        output_info += " " * indent + info_part + "\n"75    return output_info76class Record:77    """Hold GenBank information in a format similar to the original record.78    The Record class is meant to make data easy to get to when you are79    just interested in looking at GenBank data.80    Attributes:81    o locus - The name specified after the LOCUS keyword in the GenBank82    record. This may be the accession number, or a clone id or something else.83    o size - The size of the record.84    o residue_type - The type of residues making up the sequence in this85    record. Normally something like RNA, DNA or PROTEIN, but may be as86    esoteric as 'ss-RNA circular'.87    o data_file_division - The division this record is stored under in88    GenBank (ie. PLN -> plants; PRI -> humans, primates; BCT -> bacteria...)89    o date - The date of submission of the record, in a form like '28-JUL-1998'90    o accession - list of all accession numbers for the sequence.91    o nid - Nucleotide identifier number.92    o pid - Proteint identifier number93    o version - The accession number + version (ie. AB01234.2)94    o db_source - Information about the database the record came from95    o gi - The NCBI gi identifier for the record.96    o keywords - A list of keywords related to the record.97    o segment - If the record is one of a series, this is info about which98    segment this record is (something like '1 of 6').99    o source - The source of material where the sequence came from.100    o organism - The genus and species of the organism (ie. 'Homo sapiens')101    o taxonomy - A listing of the taxonomic classification of the organism,102    starting general and getting more specific.103    o references - A list of Reference objects.104    o comment - Text with any kind of comment about the record.105    o features - A listing of Features making up the feature table.106    o base_counts - A string with the counts of bases for the sequence.107    o origin - A string specifying info about the origin of the sequence.108    o sequence - A string with the sequence itself.109    o contig - A string of location information for a CONTIG in a RefSeq file110    o project - The genome sequencing project numbers111                (will be replaced by the dblink cross-references in 2009).112    o dblinks - The genome sequencing project number(s) and other links.113                (will replace the project information in 2009).114    """115    # constants for outputting GenBank information116    GB_LINE_LENGTH = 79117    GB_BASE_INDENT = 12118    GB_FEATURE_INDENT = 21119    GB_INTERNAL_INDENT = 2120    GB_OTHER_INTERNAL_INDENT = 3121    GB_FEATURE_INTERNAL_INDENT = 5122    GB_SEQUENCE_INDENT = 9123    BASE_FORMAT = "%-" + str(GB_BASE_INDENT) + "s"124    INTERNAL_FORMAT = " " * GB_INTERNAL_INDENT + "%-" + \125                      str(GB_BASE_INDENT - GB_INTERNAL_INDENT) + "s"126    OTHER_INTERNAL_FORMAT = " " * GB_OTHER_INTERNAL_INDENT + "%-" + \127                            str(GB_BASE_INDENT - GB_OTHER_INTERNAL_INDENT) + \128                            "s"129    BASE_FEATURE_FORMAT = "%-" + str(GB_FEATURE_INDENT) + "s"130    INTERNAL_FEATURE_FORMAT = " " * GB_FEATURE_INTERNAL_INDENT + "%-" + \131                              str(GB_FEATURE_INDENT -132                                  GB_FEATURE_INTERNAL_INDENT) + "s"133    SEQUENCE_FORMAT = "%" + str(GB_SEQUENCE_INDENT) + "s"134    135    def __init__(self):136        self.locus = ''137        self.size = ''138        self.residue_type = ''139        self.data_file_division = ''140        self.date = ''141        self.definition = ''142        self.accession = []143        self.nid = ''144        self.pid = ''145        self.version = ''146        self.projects = []147        self.dblinks = []148        self.db_source = ''149        self.gi = ''150        self.keywords = []151        self.segment = ''152        self.source = ''153        self.organism = ''154        self.taxonomy = []155        self.references = []156        self.comment = ''157        self.features = []158        self.base_counts = ''159        self.origin = ''160        self.sequence = ''161        self.contig = ''162        self.primary=[]163        self.wgs = ''164        self.wgs_scafld = []165    def __str__(self):166        """Provide a GenBank formatted output option for a Record.167        The objective of this is to provide an easy way to read in a GenBank168        record, modify it somehow, and then output it in 'GenBank format.'169        We are striving to make this work so that a parsed Record that is170        output using this function will look exactly like the original171        record.172        Much of the output is based on format description info at:173        ftp://ncbi.nlm.nih.gov/genbank/gbrel.txt174        """175        output = self._locus_line()176        output += self._definition_line()177        output += self._accession_line()178        output += self._version_line()179        output += self._project_line()180        output += self._dblink_line()181        output += self._nid_line()182        output += self._pid_line()183        output += self._keywords_line()184        output += self._db_source_line()185        output += self._segment_line()186        output += self._source_line()187        output += self._organism_line()188        for reference in self.references:189            output += str(reference)190        output += self._comment_line()191        output += self._features_line()192        for feature in self.features:193            output += str(feature)194        output += self._base_count_line()195        output += self._origin_line()196        output += self._sequence_line()197        output += self._wgs_line()198        output += self._wgs_scafld_line()199        output += self._contig_line()200        output += "//"201        return output202            203    def _locus_line(self):204        """Provide the output string for the LOCUS line.205        """206        output = "LOCUS"207        output += " " * 7 # 6-12 spaces208        output += "%-9s" % self.locus209        output += " " # 22 space210        output += "%7s" % self.size211        if self.residue_type.find("PROTEIN") >= 0:212            output += " aa"213        else:214            output += " bp "215        # treat circular types differently, since they'll have long residue216        # types217        if self.residue_type.find("circular") >= 0:218             output += "%17s" % self.residue_type219        # second case: ss-DNA types of records220        elif self.residue_type.find("-") >= 0:221            output += "%7s" % self.residue_type222            output += " " * 10 # spaces for circular223        else:224            output += " " * 3 # spaces for stuff like ss-225            output += "%-4s" % self.residue_type226            output += " " * 10 # spaces for circular227        output += " " * 2228        output += "%3s" % self.data_file_division229        output += " " * 7 # spaces for 56-63230        output += "%11s" % self.date231        output += "\n"232        return output233    def _definition_line(self):234        """Provide output for the DEFINITION line.235        """236        output = Record.BASE_FORMAT % "DEFINITION"237        output += _wrapped_genbank(self.definition, Record.GB_BASE_INDENT)238        return output239    def _accession_line(self):240        """Output for the ACCESSION line.241        """242        if self.accession:243            output = Record.BASE_FORMAT % "ACCESSION"244            acc_info = ""245            for accession in self.accession:246                acc_info += "%s " % accession247            # strip off an extra space at the end248            acc_info = acc_info.rstrip()249            output += _wrapped_genbank(acc_info, Record.GB_BASE_INDENT)250        else:251            output = ""252        253        return output254    def _version_line(self):255        """Output for the VERSION line.256        """257        if self.version:258            output = Record.BASE_FORMAT % "VERSION"259            output += self.version260            output += "  GI:"261            output += "%s\n" % self.gi262        else:263            output = ""264        return output265    def _project_line(self):266        output = ""267        if len(self.projects) > 0:268            output = Record.BASE_FORMAT % "PROJECT"269            output += "%s\n" % "  ".join(self.projects)270        return output271    def _dblink_line(self):272        output = ""273        if len(self.dblinks) > 0:274            output = Record.BASE_FORMAT % "DBLINK"275            dblink_info = "\n".join(self.dblinks)276            output += _wrapped_genbank(dblink_info, Record.GB_BASE_INDENT)277        return output278    def _nid_line(self):279        """Output for the NID line. Use of NID is obsolete in GenBank files.280        """281        if self.nid:282            output = Record.BASE_FORMAT % "NID"283            output += "%s\n" % self.nid284        else:285            output = ""286        return output287    def _pid_line(self):288        """Output for PID line. Presumedly, PID usage is also obsolete.289        """290        if self.pid:291            output = Record.BASE_FORMAT % "PID"292            output += "%s\n" % self.pid293        else:294            output = ""295        return output296    def _keywords_line(self):297        """Output for the KEYWORDS line.298        """299        output = ""300        if len(self.keywords) >= 0:301            output +=  Record.BASE_FORMAT % "KEYWORDS"302            keyword_info = ""303            for keyword in self.keywords:304                keyword_info += "%s; " % keyword305            # replace the ; at the end with a period306            keyword_info = keyword_info[:-2]307            keyword_info += "."308            309            output += _wrapped_genbank(keyword_info,310                                       Record.GB_BASE_INDENT)311        return output312    def _db_source_line(self):313        """Output for DBSOURCE line.314        """315        if self.db_source:316            output = Record.BASE_FORMAT % "DBSOURCE"317            output += "%s\n" % self.db_source318        else:319            output = ""320        return output321    def _segment_line(self):322        """Output for the SEGMENT line.323        """324        output = ""325        if self.segment:326            output += Record.BASE_FORMAT % "SEGMENT"327            output += _wrapped_genbank(self.segment, Record.GB_BASE_INDENT)328        return output329    def _source_line(self):330        """Output for SOURCE line on where the sample came from.331        """332        output = Record.BASE_FORMAT % "SOURCE"333        output += _wrapped_genbank(self.source, Record.GB_BASE_INDENT)334        return output335    336    def _organism_line(self):337        """Output for ORGANISM line with taxonomy info.338        """339        output = Record.INTERNAL_FORMAT % "ORGANISM"340        # Now that species names can be too long, this line can wrap (Bug 2591)341        output += _wrapped_genbank(self.organism, Record.GB_BASE_INDENT)342        output += " " * Record.GB_BASE_INDENT343        taxonomy_info = ""344        for tax in self.taxonomy:345            taxonomy_info += "%s; " % tax346        # replace the ; at the end with a period347        taxonomy_info = taxonomy_info[:-2]348        taxonomy_info += "."349        output += _wrapped_genbank(taxonomy_info, Record.GB_BASE_INDENT)350        return output351            352    def _comment_line(self):353        """Output for the COMMENT lines.354        """355        output = ""356        if self.comment:357            output += Record.BASE_FORMAT % "COMMENT"358            output += _indent_genbank(self.comment,359                                      Record.GB_BASE_INDENT)360        return output361    def _features_line(self):362        """Output for the FEATURES line.363        """364        output = ""365        if len(self.features) > 0:366            output += Record.BASE_FEATURE_FORMAT % "FEATURES"367            output += "Location/Qualifiers\n"368        return output369    def _base_count_line(self):370        """Output for the BASE COUNT line with base information.371        """372        output = ""373        if self.base_counts:374            output += Record.BASE_FORMAT % "BASE COUNT  "375            # split up the base counts into their individual parts376            count_parts = self.base_counts.split(" ")377            while '' in count_parts:378                count_parts.remove('')379            # deal with the standard case, with a normal origin line380            # like: 474 a    356 c    428 g    364 t381            if len(count_parts) % 2 == 0:382                while len(count_parts) > 0:383                    count_info = count_parts.pop(0)384                    count_type = count_parts.pop(0)385                    output += "%7s %s" % (count_info, count_type)386            # deal with ugly ORIGIN lines like:387            # 1311257 a2224835 c2190093 g1309889 t388            # by just outputting the raw information389            else:390                output += self.base_counts391            output += "\n"392        return output393    def _origin_line(self):394        """Output for the ORIGIN line395        """396        output = ""397        # only output the ORIGIN line if we have a sequence398        if self.sequence:399            output += Record.BASE_FORMAT % "ORIGIN"400            if self.origin:401                output += _wrapped_genbank(self.origin,402                                           Record.GB_BASE_INDENT)403            else:404                output += "\n"405        return output406    def _sequence_line(self):407        """Output for all of the sequence.408        """409        output = ""410        if self.sequence:411            cur_seq_pos = 0412            while cur_seq_pos < len(self.sequence):413                output += Record.SEQUENCE_FORMAT % str(cur_seq_pos + 1)414                for section in range(6):415                    start_pos = cur_seq_pos + section * 10416                    end_pos = start_pos + 10417                    seq_section = self.sequence[start_pos:end_pos]418                    output += " %s" % seq_section.lower()419                    # stop looping if we are out of sequence420                    if end_pos > len(self.sequence):421                        break422                423                output += "\n"424                cur_seq_pos += 60425        return output426    def _wgs_line(self):427            output = ""428            if self.wgs:429                    output += Record.BASE_FORMAT % "WGS"430                    output += self.wgs431            return output432    def _wgs_scafld_line(self):433            output = ""434            if self.wgs_scafld:435                    output += Record.BASE_FORMAT % "WGS_SCAFLD"436                    output += self.wgs_scafld437            return output438        439    def _contig_line(self):440        """Output for CONTIG location information from RefSeq.441        """442        output = ""443        if self.contig:444            output += Record.BASE_FORMAT % "CONTIG"445            output += _wrapped_genbank(self.contig,446                                       Record.GB_BASE_INDENT, split_char = ',')447        return output448        449class Reference:450    """Hold information from a GenBank reference.451    Attributes:452    o number - The number of the reference in the listing of references.453    o bases - The bases in the sequence the reference refers to.454    o authors - String with all of the authors.455    o consrtm - Consortium the authors belong to. 456    o title - The title of the reference.457    o journal - Information about the journal where the reference appeared.458    o medline_id - The medline id for the reference.459    o pubmed_id - The pubmed_id for the reference.460    o remark - Free-form remarks about the reference.461    """462    def __init__(self):463        self.number = ''464        self.bases = ''465        self.authors = ''466        self.consrtm = ''467        self.title = ''468        self.journal = ''469        self.medline_id = ''470        self.pubmed_id = ''471        self.remark = ''472    def __str__(self):473        output = self._reference_line()474        output += self._authors_line()475        output += self._consrtm_line()476        output += self._title_line()477        output += self._journal_line()478        output += self._medline_line()479        output += self._pubmed_line()480        output += self._remark_line()481        482        return output483    def _reference_line(self):484        """Output for REFERENCE lines.485        """486        output = Record.BASE_FORMAT % "REFERENCE"487        if self.number:488            if self.bases:489                output += "%-3s" % self.number490                output += "%s" % self.bases491            else:492                output += "%s" % self.number493        output += "\n"494        return output495    def _authors_line(self):496        """Output for AUTHORS information.497        """498        output = ""499        if self.authors:500            output += Record.INTERNAL_FORMAT % "AUTHORS"501            output += _wrapped_genbank(self.authors, Record.GB_BASE_INDENT)502        return output503    def _consrtm_line(self):504        """Output for CONSRTM information.505        """506        output = ""507        if self.consrtm:508            output += Record.INTERNAL_FORMAT % "CONSRTM"509            output += _wrapped_genbank(self.consrtm, Record.GB_BASE_INDENT)510        return output511    def _title_line(self):512        """Output for TITLE information.513        """514        output = ""515        if self.title:516            output += Record.INTERNAL_FORMAT % "TITLE"517            output += _wrapped_genbank(self.title, Record.GB_BASE_INDENT)518        return output519    def _journal_line(self):520        """Output for JOURNAL information.521        """522        output = ""523        if self.journal:524            output += Record.INTERNAL_FORMAT % "JOURNAL"525            output += _wrapped_genbank(self.journal, Record.GB_BASE_INDENT)526        return output527    def _medline_line(self):528        """Output for MEDLINE information.529        """530        output = ""531        if self.medline_id:532            output += Record.INTERNAL_FORMAT % "MEDLINE"533            output += self.medline_id + "\n"534        return output535    536    def _pubmed_line(self):537        """Output for PUBMED information.538        """539        output = ""540        if self.pubmed_id:541            output += Record.OTHER_INTERNAL_FORMAT % "PUBMED"542            output += self.pubmed_id + "\n"543        return output544    545    def _remark_line(self):546        """Output for REMARK information.547        """548        output = ""549        if self.remark:550            output += Record.INTERNAL_FORMAT % "REMARK"551            output += _wrapped_genbank(self.remark, Record.GB_BASE_INDENT)552        return output553    554class Feature:555    """Hold information about a Feature in the Feature Table of GenBank record.556    Attributes:557    o key - The key name of the featue (ie. source)558    o location - The string specifying the location of the feature.559    o qualfiers - A listing Qualifier objects in the feature.560    """561    def __init__(self):562        self.key = ''563        self.location = ''564        self.qualifiers = []565    def __str__(self):566        output = Record.INTERNAL_FEATURE_FORMAT % self.key567        output += _wrapped_genbank(self.location, Record.GB_FEATURE_INDENT,568                                   split_char = ',')569        for qualifier in self.qualifiers:570            output += " " * Record.GB_FEATURE_INDENT571            572            # determine whether we can wrap on spaces573            space_wrap = 1574            for no_space_key in \575                Bio.GenBank._BaseGenBankConsumer.remove_space_keys:576                if qualifier.key.find(no_space_key) >= 0:577                    space_wrap = 0578            579            output += _wrapped_genbank(qualifier.key + qualifier.value,580                                       Record.GB_FEATURE_INDENT, space_wrap)581        return output582class Qualifier:583    """Hold information about a qualifier in a GenBank feature.584    Attributes:585    o key - The key name of the qualifier (ie. /organism=)586    o value - The value of the qualifier ("Dictyostelium discoideum").587    """588    def __init__(self):589        self.key = ''...bgenObjectDefinition.py
Source:bgenObjectDefinition.py  
1from bgenOutput import *2from bgenGeneratorGroup import GeneratorGroup3class ObjectDefinition(GeneratorGroup):4    "Spit out code that together defines a new Python object type"5    basechain = "NULL"6    tp_flags = "Py_TPFLAGS_DEFAULT"7    basetype = None8    argref = ""    # set to "*" if arg to <type>_New should be pointer9    argconst = ""   # set to "const " if arg to <type>_New should be const10    def __init__(self, name, prefix, itselftype):11        """ObjectDefinition constructor.  May be extended, but do not override.12        - name: the object's official name, e.g. 'SndChannel'.13        - prefix: the prefix used for the object's functions and data, e.g. 'SndCh'.14        - itselftype: the C type actually contained in the object, e.g. 'SndChannelPtr'.15        XXX For official Python data types, rules for the 'Py' prefix are a problem.16        """17        GeneratorGroup.__init__(self, prefix or name)18        self.name = name19        self.itselftype = itselftype20        self.objecttype = name + 'Object'21        self.typename = name + '_Type'22        self.static = "static " # set to "" to make <type>_New and <type>_Convert public23        self.modulename = None24        if hasattr(self, "assertions"):25            self.assertions()26    def add(self, g, dupcheck=0):27        g.setselftype(self.objecttype, self.itselftype)28        GeneratorGroup.add(self, g, dupcheck)29    def reference(self):30        # In case we are referenced from a module31        pass32    def setmodulename(self, name):33        self.modulename = name34    def generate(self):35        # XXX This should use long strings and %(varname)s substitution!36        OutHeader2("Object type " + self.name)37        self.outputCheck()38        Output("typedef struct %s {", self.objecttype)39        IndentLevel()40        Output("PyObject_HEAD")41        self.outputStructMembers()42        DedentLevel()43        Output("} %s;", self.objecttype)44        self.outputNew()45        self.outputConvert()46        self.outputDealloc()47        GeneratorGroup.generate(self)48        Output()49        self.outputMethodChain()50        self.outputGetattr()51        self.outputSetattr()52        self.outputCompare()53        self.outputRepr()54        self.outputHash()55        self.outputPEP253Hooks()56        self.outputTypeObject()57        OutHeader2("End object type " + self.name)58    def outputCheck(self):59        sf = self.static and "static "60        Output("%sPyTypeObject %s;", sf, self.typename)61        Output()62        Output("#define %s_Check(x) ((x)->ob_type == &%s || PyObject_TypeCheck((x), &%s))",63               self.prefix, self.typename, self.typename)64        Output()65    def outputMethodChain(self):66        Output("%sPyMethodChain %s_chain = { %s_methods, %s };",67                self.static,    self.prefix, self.prefix, self.basechain)68    def outputStructMembers(self):69        Output("%s ob_itself;", self.itselftype)70    def outputNew(self):71        Output()72        Output("%sPyObject *%s_New(%s%s %sitself)", self.static, self.prefix,73                self.argconst, self.itselftype, self.argref)74        OutLbrace()75        Output("%s *it;", self.objecttype)76        self.outputCheckNewArg()77        Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename)78        Output("if (it == NULL) return NULL;")79        if self.basetype:80            Output("/* XXXX Should we tp_init or tp_new our basetype? */")81        self.outputInitStructMembers()82        Output("return (PyObject *)it;")83        OutRbrace()84    def outputInitStructMembers(self):85        Output("it->ob_itself = %sitself;", self.argref)86    def outputCheckNewArg(self):87        "Override this method to apply additional checks/conversions"88    def outputConvert(self):89        Output()90        Output("%sint %s_Convert(PyObject *v, %s *p_itself)", self.static, self.prefix,91                self.itselftype)92        OutLbrace()93        self.outputCheckConvertArg()94        Output("if (!%s_Check(v))", self.prefix)95        OutLbrace()96        Output('PyErr_SetString(PyExc_TypeError, "%s required");', self.name)97        Output("return 0;")98        OutRbrace()99        Output("*p_itself = ((%s *)v)->ob_itself;", self.objecttype)100        Output("return 1;")101        OutRbrace()102    def outputCheckConvertArg(self):103        "Override this method to apply additional conversions"104    def outputDealloc(self):105        Output()106        Output("static void %s_dealloc(%s *self)", self.prefix, self.objecttype)107        OutLbrace()108        self.outputCleanupStructMembers()109        if self.basetype:110            Output("%s.tp_dealloc((PyObject *)self);", self.basetype)111        elif hasattr(self, 'output_tp_free'):112            # This is a new-style object with tp_free slot113            Output("self->ob_type->tp_free((PyObject *)self);")114        else:115            Output("PyObject_Free((PyObject *)self);")116        OutRbrace()117    def outputCleanupStructMembers(self):118        self.outputFreeIt("self->ob_itself")119    def outputFreeIt(self, name):120        Output("/* Cleanup of %s goes here */", name)121    def outputGetattr(self):122        Output()123        Output("static PyObject *%s_getattr(%s *self, char *name)", self.prefix, self.objecttype)124        OutLbrace()125        self.outputGetattrBody()126        OutRbrace()127    def outputGetattrBody(self):128        self.outputGetattrHook()129        Output("return Py_FindMethodInChain(&%s_chain, (PyObject *)self, name);",130               self.prefix)131    def outputGetattrHook(self):132        pass133    def outputSetattr(self):134        Output()135        Output("#define %s_setattr NULL", self.prefix)136    def outputCompare(self):137        Output()138        Output("#define %s_compare NULL", self.prefix)139    def outputRepr(self):140        Output()141        Output("#define %s_repr NULL", self.prefix)142    def outputHash(self):143        Output()144        Output("#define %s_hash NULL", self.prefix)145    def outputTypeObject(self):146        sf = self.static and "static "147        Output()148        Output("%sPyTypeObject %s = {", sf, self.typename)149        IndentLevel()150        Output("PyObject_HEAD_INIT(NULL)")151        Output("0, /*ob_size*/")152        if self.modulename:153            Output("\"%s.%s\", /*tp_name*/", self.modulename, self.name)154        else:155            Output("\"%s\", /*tp_name*/", self.name)156        Output("sizeof(%s), /*tp_basicsize*/", self.objecttype)157        Output("0, /*tp_itemsize*/")158        Output("/* methods */")159        Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix)160        Output("0, /*tp_print*/")161        Output("(getattrfunc) %s_getattr, /*tp_getattr*/", self.prefix)162        Output("(setattrfunc) %s_setattr, /*tp_setattr*/", self.prefix)163        Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix)164        Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix)165        Output("(PyNumberMethods *)0, /* tp_as_number */")166        Output("(PySequenceMethods *)0, /* tp_as_sequence */")167        Output("(PyMappingMethods *)0, /* tp_as_mapping */")168        Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)169        DedentLevel()170        Output("};")171    def outputTypeObjectInitializer(self):172        Output("""%s.ob_type = &PyType_Type;""", self.typename)173        if self.basetype:174            Output("%s.tp_base = &%s;", self.typename, self.basetype)175        Output("if (PyType_Ready(&%s) < 0) return;", self.typename)176        Output("""Py_INCREF(&%s);""", self.typename)177        Output("PyModule_AddObject(m, \"%s\", (PyObject *)&%s);", self.name, self.typename);178        self.outputTypeObjectInitializerCompat()179    def outputTypeObjectInitializerCompat(self):180        Output("/* Backward-compatible name */")181        Output("""Py_INCREF(&%s);""", self.typename);182        Output("PyModule_AddObject(m, \"%sType\", (PyObject *)&%s);", self.name, self.typename);183    def outputPEP253Hooks(self):184        pass185class PEP252Mixin:186    getsetlist = []187    def assertions(self):188        # Check that various things aren't overridden. If they are it could189        # signify a bgen-client that has been partially converted to PEP252.190        assert self.outputGetattr.im_func == PEP252Mixin.outputGetattr.im_func191        assert self.outputSetattr.im_func == PEP252Mixin.outputSetattr.im_func192        assert self.outputGetattrBody == None193        assert self.outputGetattrHook == None194        assert self.basechain == "NULL"195    def outputGetattr(self):196        pass197    outputGetattrBody = None198    outputGetattrHook = None199    def outputSetattr(self):200        pass201    def outputMethodChain(self):202        # This is a good place to output the getters and setters203        self.outputGetSetList()204    def outputHook(self, name):205        methodname = "outputHook_" + name206        if hasattr(self, methodname):207            func = getattr(self, methodname)208            func()209        else:210            Output("0, /*%s*/", name)211    def outputTypeObject(self):212        sf = self.static and "static "213        Output()214        Output("%sPyTypeObject %s = {", sf, self.typename)215        IndentLevel()216        Output("PyObject_HEAD_INIT(NULL)")217        Output("0, /*ob_size*/")218        if self.modulename:219            Output("\"%s.%s\", /*tp_name*/", self.modulename, self.name)220        else:221            Output("\"%s\", /*tp_name*/", self.name)222        Output("sizeof(%s), /*tp_basicsize*/", self.objecttype)223        Output("0, /*tp_itemsize*/")224        Output("/* methods */")225        Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix)226        Output("0, /*tp_print*/")227        Output("(getattrfunc)0, /*tp_getattr*/")228        Output("(setattrfunc)0, /*tp_setattr*/")229        Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix)230        Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix)231        Output("(PyNumberMethods *)0, /* tp_as_number */")232        Output("(PySequenceMethods *)0, /* tp_as_sequence */")233        Output("(PyMappingMethods *)0, /* tp_as_mapping */")234        Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)235        self.outputHook("tp_call")236        Output("0, /*tp_str*/")237        Output("PyObject_GenericGetAttr, /*tp_getattro*/")238        Output("PyObject_GenericSetAttr, /*tp_setattro */")239        self.outputHook("tp_as_buffer")240        Output("%s, /* tp_flags */", self.tp_flags)241        self.outputHook("tp_doc")242        self.outputHook("tp_traverse")243        self.outputHook("tp_clear")244        self.outputHook("tp_richcompare")245        self.outputHook("tp_weaklistoffset")246        self.outputHook("tp_iter")247        self.outputHook("tp_iternext")248        Output("%s_methods, /* tp_methods */", self.prefix)249        self.outputHook("tp_members")250        Output("%s_getsetlist, /*tp_getset*/", self.prefix)251        self.outputHook("tp_base")252        self.outputHook("tp_dict")253        self.outputHook("tp_descr_get")254        self.outputHook("tp_descr_set")255        self.outputHook("tp_dictoffset")256        self.outputHook("tp_init")257        self.outputHook("tp_alloc")258        self.outputHook("tp_new")259        self.outputHook("tp_free")260        DedentLevel()261        Output("};")262    def outputGetSetList(self):263        if self.getsetlist:264            for name, get, set, doc in self.getsetlist:265                if get:266                    self.outputGetter(name, get)267                else:268                    Output("#define %s_get_%s NULL", self.prefix, name)269                    Output()270                if set:271                    self.outputSetter(name, set)272                else:273                    Output("#define %s_set_%s NULL", self.prefix, name)274                    Output()275            Output("static PyGetSetDef %s_getsetlist[] = {", self.prefix)276            IndentLevel()277            for name, get, set, doc in self.getsetlist:278                if doc:279                    doc = '"' + doc + '"'280                else:281                    doc = "NULL"282                Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s},",283                    name, self.prefix, name, self.prefix, name, doc)284            Output("{NULL, NULL, NULL, NULL},")285            DedentLevel()286            Output("};")287        else:288            Output("#define %s_getsetlist NULL", self.prefix)289        Output()290    def outputGetter(self, name, code):291        Output("static PyObject *%s_get_%s(%s *self, void *closure)",292            self.prefix, name, self.objecttype)293        OutLbrace()294        Output(code)295        OutRbrace()296        Output()297    def outputSetter(self, name, code):298        Output("static int %s_set_%s(%s *self, PyObject *v, void *closure)",299            self.prefix, name, self.objecttype)300        OutLbrace()301        Output(code)302        Output("return 0;")303        OutRbrace()304        Output()305class PEP253Mixin(PEP252Mixin):306    tp_flags = "Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"307    def outputHook_tp_init(self):308        Output("%s_tp_init, /* tp_init */", self.prefix)309    def outputHook_tp_alloc(self):310        Output("%s_tp_alloc, /* tp_alloc */", self.prefix)311    def outputHook_tp_new(self):312        Output("%s_tp_new, /* tp_new */", self.prefix)313    def outputHook_tp_free(self):314        Output("%s_tp_free, /* tp_free */", self.prefix)315    def output_tp_initBody_basecall(self):316        """If a type shares its init call with its base type set output_tp_initBody317        to output_tp_initBody_basecall"""318        if self.basetype:319            Output("if (%s.tp_init)", self.basetype)320            OutLbrace()321            Output("if ( (*%s.tp_init)(_self, _args, _kwds) < 0) return -1;", self.basetype)322            OutRbrace()323    output_tp_initBody = None324    def output_tp_init(self):325        if self.output_tp_initBody:326            Output("static int %s_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)", self.prefix)327            OutLbrace()328            self.output_tp_initBody()329            OutRbrace()330        else:331            Output("#define %s_tp_init 0", self.prefix)332        Output()333    output_tp_allocBody = None334    def output_tp_alloc(self):335        if self.output_tp_allocBody:336            Output("static PyObject *%s_tp_alloc(PyTypeObject *type, int nitems)",337                self.prefix)338            OutLbrace()339            self.output_tp_allocBody()340            OutRbrace()341        else:342            Output("#define %s_tp_alloc PyType_GenericAlloc", self.prefix)343        Output()344    def output_tp_newBody(self):345        Output("PyObject *_self;");346        Output("%s itself;", self.itselftype);347        Output("char *kw[] = {\"itself\", 0};")348        Output()349        Output("if (!PyArg_ParseTupleAndKeywords(_args, _kwds, \"O&\", kw, %s_Convert, &itself)) return NULL;",350            self.prefix);351        if self.basetype:352            Output("if (%s.tp_new)", self.basetype)353            OutLbrace()354            Output("if ( (*%s.tp_new)(type, _args, _kwds) == NULL) return NULL;", self.basetype)355            Dedent()356            Output("} else {")357            Indent()358            Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;")359            OutRbrace()360        else:361            Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;")362        Output("((%s *)_self)->ob_itself = itself;", self.objecttype)363        Output("return _self;")364    def output_tp_new(self):365        if self.output_tp_newBody:366            Output("static PyObject *%s_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)", self.prefix)367            OutLbrace()368            self.output_tp_newBody()369            OutRbrace()370        else:371            Output("#define %s_tp_new PyType_GenericNew", self.prefix)372        Output()373    output_tp_freeBody = None374    def output_tp_free(self):375        if self.output_tp_freeBody:376            Output("static void %s_tp_free(PyObject *self)", self.prefix)377            OutLbrace()378            self.output_tp_freeBody()379            OutRbrace()380        else:381            Output("#define %s_tp_free PyObject_Del", self.prefix)382        Output()383    def outputPEP253Hooks(self):384        self.output_tp_init()385        self.output_tp_alloc()386        self.output_tp_new()387        self.output_tp_free()388class GlobalObjectDefinition(ObjectDefinition):389    """Like ObjectDefinition but exports some parts.390    XXX Should also somehow generate a .h file for them.391    """392    def __init__(self, name, prefix = None, itselftype = None):393        ObjectDefinition.__init__(self, name, prefix or name, itselftype or name)394        self.static = ""395class ObjectIdentityMixin:396    """A mixin class for objects that makes the identity of ob_itself397    govern comparisons and dictionary lookups. Useful if the C object can398    be returned by library calls and it is difficult (or impossible) to find399    the corresponding Python objects. With this you can create Python object400    wrappers on the fly"""401    def outputCompare(self):402        Output()403        Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype,404                self.objecttype)405        OutLbrace()406        Output("unsigned long v, w;")407        Output()408        Output("if (!%s_Check((PyObject *)other))", self.prefix)409        OutLbrace()410        Output("v=(unsigned long)self;")411        Output("w=(unsigned long)other;")412        OutRbrace()413        Output("else")414        OutLbrace()415        Output("v=(unsigned long)self->ob_itself;")416        Output("w=(unsigned long)other->ob_itself;")417        OutRbrace()418        Output("if( v < w ) return -1;")419        Output("if( v > w ) return 1;")420        Output("return 0;")421        OutRbrace()422    def outputHash(self):423        Output()424        Output("static long %s_hash(%s *self)", self.prefix, self.objecttype)425        OutLbrace()426        Output("return (long)self->ob_itself;")...grid_output.py
Source:grid_output.py  
...65        :rtype: GridOutput66        """67        return util.deserialize_model(dikt, cls)68    @property69    def p_grid_output(self) -> SourceOutput:70        """Gets the p_grid_output of this GridOutput.71        :return: The p_grid_output of this GridOutput.72        :rtype: SourceOutput73        """74        return self._p_grid_output75    @p_grid_output.setter76    def p_grid_output(self, p_grid_output: SourceOutput):77        """Sets the p_grid_output of this GridOutput.78        :param p_grid_output: The p_grid_output of this GridOutput.79        :type p_grid_output: SourceOutput80        """81        self._p_grid_output = p_grid_output82    @property83    def p_grid_r_output(self) -> SourceOutput:84        """Gets the p_grid_r_output of this GridOutput.85        :return: The p_grid_r_output of this GridOutput.86        :rtype: SourceOutput87        """88        return self._p_grid_r_output89    @p_grid_r_output.setter90    def p_grid_r_output(self, p_grid_r_output: SourceOutput):91        """Sets the p_grid_r_output of this GridOutput.92        :param p_grid_r_output: The p_grid_r_output of this GridOutput.93        :type p_grid_r_output: SourceOutput94        """95        self._p_grid_r_output = p_grid_r_output96    @property97    def p_grid_s_output(self) -> SourceOutput:98        """Gets the p_grid_s_output of this GridOutput.99        :return: The p_grid_s_output of this GridOutput.100        :rtype: SourceOutput101        """102        return self._p_grid_s_output103    @p_grid_s_output.setter104    def p_grid_s_output(self, p_grid_s_output: SourceOutput):105        """Sets the p_grid_s_output of this GridOutput.106        :param p_grid_s_output: The p_grid_s_output of this GridOutput.107        :type p_grid_s_output: SourceOutput108        """109        self._p_grid_s_output = p_grid_s_output110    @property111    def p_grid_t_output(self) -> SourceOutput:112        """Gets the p_grid_t_output of this GridOutput.113        :return: The p_grid_t_output of this GridOutput.114        :rtype: SourceOutput115        """116        return self._p_grid_t_output117    @p_grid_t_output.setter118    def p_grid_t_output(self, p_grid_t_output: SourceOutput):119        """Sets the p_grid_t_output of this GridOutput.120        :param p_grid_t_output: The p_grid_t_output of this GridOutput.121        :type p_grid_t_output: SourceOutput122        """123        self._p_grid_t_output = p_grid_t_output124    @property125    def q_grid_output(self) -> SourceOutput:126        """Gets the q_grid_output of this GridOutput.127        :return: The q_grid_output of this GridOutput.128        :rtype: SourceOutput129        """130        return self._q_grid_output131    @q_grid_output.setter132    def q_grid_output(self, q_grid_output: SourceOutput):133        """Sets the q_grid_output of this GridOutput.134        :param q_grid_output: The q_grid_output of this GridOutput.135        :type q_grid_output: SourceOutput136        """137        self._q_grid_output = q_grid_output138    @property139    def q_grid_r_output(self) -> SourceOutput:140        """Gets the q_grid_r_output of this GridOutput.141        :return: The q_grid_r_output of this GridOutput.142        :rtype: SourceOutput143        """144        return self._q_grid_r_output145    @q_grid_r_output.setter146    def q_grid_r_output(self, q_grid_r_output: SourceOutput):147        """Sets the q_grid_r_output of this GridOutput.148        :param q_grid_r_output: The q_grid_r_output of this GridOutput.149        :type q_grid_r_output: SourceOutput150        """151        self._q_grid_r_output = q_grid_r_output152    @property153    def q_grid_s_output(self) -> SourceOutput:154        """Gets the q_grid_s_output of this GridOutput.155        :return: The q_grid_s_output of this GridOutput.156        :rtype: SourceOutput157        """158        return self._q_grid_s_output159    @q_grid_s_output.setter160    def q_grid_s_output(self, q_grid_s_output: SourceOutput):161        """Sets the q_grid_s_output of this GridOutput.162        :param q_grid_s_output: The q_grid_s_output of this GridOutput.163        :type q_grid_s_output: SourceOutput164        """165        self._q_grid_s_output = q_grid_s_output166    @property167    def q_grid_t_output(self) -> SourceOutput:168        """Gets the q_grid_t_output of this GridOutput.169        :return: The q_grid_t_output of this GridOutput.170        :rtype: SourceOutput171        """172        return self._q_grid_t_output173    @q_grid_t_output.setter174    def q_grid_t_output(self, q_grid_t_output: SourceOutput):175        """Sets the q_grid_t_output of this GridOutput.176        :param q_grid_t_output: The q_grid_t_output of this GridOutput.177        :type q_grid_t_output: SourceOutput178        """...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
