Show More
@@ -76,10 +76,12 b' def extract_code_ranges(ranges_str):' | |||||
76 | start = int(start) - 1 |
|
76 | start = int(start) - 1 | |
77 | yield (start, end) |
|
77 | yield (start, end) | |
78 |
|
78 | |||
|
79 | ||||
|
80 | @skip_doctest | |||
79 | def extract_symbols(code, symbols): |
|
81 | def extract_symbols(code, symbols): | |
80 | """ |
|
82 | """ | |
81 | Return a list of code fragments for each symbol parsed from code |
|
83 | Return a list of code fragments for each symbol parsed from code | |
82 | For example, suppose code is:: |
|
84 | For example, suppose code is a string:: | |
83 |
|
85 | |||
84 | a = 10 |
|
86 | a = 10 | |
85 |
|
87 | |||
@@ -87,27 +89,35 b' def extract_symbols(code, symbols):' | |||||
87 |
|
89 | |||
88 | class A: pass |
|
90 | class A: pass | |
89 |
|
91 | |||
90 |
>>> extract_symbols(code, 'A,b') |
|
92 | >>> extract_symbols(code, 'A,b') | |
91 | class A: pass |
|
|||
92 |
|
93 | |||
93 | def b(): return 42 |
|
94 | ["class A: pass", "def b(): return 42"] | |
94 | """ |
|
95 | """ | |
95 | try: |
|
96 | try: | |
96 | py_code = ast.parse(code) |
|
97 | py_code = ast.parse(code) | |
97 | except SyntaxError: |
|
98 | except SyntaxError: | |
|
99 | # ignores non python code | |||
98 | return [] |
|
100 | return [] | |
|
101 | ||||
99 | marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body] |
|
102 | marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body] | |
|
103 | ||||
|
104 | # construct a dictionary with elements | |||
|
105 | # {'symbol_name': (start_lineno, end_lineno), ...} | |||
100 | end = None |
|
106 | end = None | |
101 | symbols_lines = {} |
|
107 | symbols_lines = {} | |
102 | for name, start in reversed(marks): |
|
108 | for name, start in reversed(marks): | |
103 | if name: |
|
109 | if name: | |
104 | symbols_lines[name] = (start - 1, end) |
|
110 | symbols_lines[name] = (start - 1, end) | |
105 | end = start - 1 |
|
111 | end = start - 1 | |
|
112 | ||||
|
113 | # fill a list with chunks of codes for each symbol | |||
106 | blocks = [] |
|
114 | blocks = [] | |
107 | code = code.split('\n') |
|
115 | code = code.split('\n') | |
108 | for symbol in symbols.split(','): |
|
116 | for symbol in symbols.split(','): | |
109 | if symbol in symbols_lines: |
|
117 | if symbol in symbols_lines: | |
110 |
|
|
118 | start, end = symbols_lines[symbol] | |
|
119 | blocks.append('\n'.join(code[start:end])) | |||
|
120 | ||||
111 | return blocks |
|
121 | return blocks | |
112 |
|
122 | |||
113 |
|
123 |
General Comments 0
You need to be logged in to leave comments.
Login now