Given a path to a Python source file, extracts line numbers for all lines that are marked with #@. For example, given this file:: print(1) # @foo print(2) print(3) # @bar,baz the function will return:: {"foo": 1, "bar": 3, "baz": 3}
(path)
| 12 | |
| 13 | |
| 14 | def get_marked_line_numbers(path): |
| 15 | """Given a path to a Python source file, extracts line numbers for all lines |
| 16 | that are marked with #@. For example, given this file:: |
| 17 | |
| 18 | print(1) # @foo |
| 19 | print(2) |
| 20 | print(3) # @bar,baz |
| 21 | |
| 22 | the function will return:: |
| 23 | |
| 24 | {"foo": 1, "bar": 3, "baz": 3} |
| 25 | """ |
| 26 | |
| 27 | if isinstance(path, py.path.local): |
| 28 | path = path.strpath |
| 29 | |
| 30 | try: |
| 31 | return _marked_line_numbers_cache[path] |
| 32 | except KeyError: |
| 33 | pass |
| 34 | |
| 35 | # Read as bytes to avoid decoding errors. |
| 36 | with open(path, "rb") as f: |
| 37 | lines = {} |
| 38 | for i, line in enumerate(f): |
| 39 | match = re.search(rb"#\s*@(.+?)\s*$", line) |
| 40 | if match: |
| 41 | markers = match.group(1).decode("ascii") |
| 42 | for marker in markers.split(","): |
| 43 | lines[marker] = i + 1 |
| 44 | |
| 45 | _marked_line_numbers_cache[path] = lines |
| 46 | return lines |
no test coverage detected
searching dependent graphs…