Get lines of comments immediately preceding an object's source code. Returns None when source can't be found.
(object)
| 1031 | raise OSError('could not find code object') |
| 1032 | |
| 1033 | def getcomments(object): |
| 1034 | """Get lines of comments immediately preceding an object's source code. |
| 1035 | |
| 1036 | Returns None when source can't be found. |
| 1037 | """ |
| 1038 | try: |
| 1039 | lines, lnum = findsource(object) |
| 1040 | except (OSError, TypeError): |
| 1041 | return None |
| 1042 | |
| 1043 | if ismodule(object): |
| 1044 | # Look for a comment block at the top of the file. |
| 1045 | start = 0 |
| 1046 | if lines and lines[0][:2] == '#!': start = 1 |
| 1047 | while start < len(lines) and lines[start].strip() in ('', '#'): |
| 1048 | start = start + 1 |
| 1049 | if start < len(lines) and lines[start][:1] == '#': |
| 1050 | comments = [] |
| 1051 | end = start |
| 1052 | while end < len(lines) and lines[end][:1] == '#': |
| 1053 | comments.append(lines[end].expandtabs()) |
| 1054 | end = end + 1 |
| 1055 | return ''.join(comments) |
| 1056 | |
| 1057 | # Look for a preceding block of comments at the same indentation. |
| 1058 | elif lnum > 0: |
| 1059 | indent = indentsize(lines[lnum]) |
| 1060 | end = lnum - 1 |
| 1061 | if end >= 0 and lines[end].lstrip()[:1] == '#' and \ |
| 1062 | indentsize(lines[end]) == indent: |
| 1063 | comments = [lines[end].expandtabs().lstrip()] |
| 1064 | if end > 0: |
| 1065 | end = end - 1 |
| 1066 | comment = lines[end].expandtabs().lstrip() |
| 1067 | while comment[:1] == '#' and indentsize(lines[end]) == indent: |
| 1068 | comments[:0] = [comment] |
| 1069 | end = end - 1 |
| 1070 | if end < 0: break |
| 1071 | comment = lines[end].expandtabs().lstrip() |
| 1072 | while comments and comments[0].strip() == '#': |
| 1073 | comments[:1] = [] |
| 1074 | while comments and comments[-1].strip() == '#': |
| 1075 | comments[-1:] = [] |
| 1076 | return ''.join(comments) |
| 1077 | |
| 1078 | class EndOfBlock(Exception): pass |
| 1079 |
nothing calls this directly
no test coverage detected
searching dependent graphs…