Get lines of comments immediately preceding an object's source code. Returns None when source can't be found.
(object)
| 1117 | raise OSError('could not find code object') |
| 1118 | |
| 1119 | def getcomments(object): |
| 1120 | """Get lines of comments immediately preceding an object's source code. |
| 1121 | |
| 1122 | Returns None when source can't be found. |
| 1123 | """ |
| 1124 | try: |
| 1125 | lines, lnum = findsource(object) |
| 1126 | except (OSError, TypeError): |
| 1127 | return None |
| 1128 | |
| 1129 | if ismodule(object): |
| 1130 | # Look for a comment block at the top of the file. |
| 1131 | start = 0 |
| 1132 | if lines and lines[0][:2] == '#!': start = 1 |
| 1133 | while start < len(lines) and lines[start].strip() in ('', '#'): |
| 1134 | start = start + 1 |
| 1135 | if start < len(lines) and lines[start][:1] == '#': |
| 1136 | comments = [] |
| 1137 | end = start |
| 1138 | while end < len(lines) and lines[end][:1] == '#': |
| 1139 | comments.append(lines[end].expandtabs()) |
| 1140 | end = end + 1 |
| 1141 | return ''.join(comments) |
| 1142 | |
| 1143 | # Look for a preceding block of comments at the same indentation. |
| 1144 | elif lnum > 0: |
| 1145 | indent = indentsize(lines[lnum]) |
| 1146 | end = lnum - 1 |
| 1147 | if end >= 0 and lines[end].lstrip()[:1] == '#' and \ |
| 1148 | indentsize(lines[end]) == indent: |
| 1149 | comments = [lines[end].expandtabs().lstrip()] |
| 1150 | if end > 0: |
| 1151 | end = end - 1 |
| 1152 | comment = lines[end].expandtabs().lstrip() |
| 1153 | while comment[:1] == '#' and indentsize(lines[end]) == indent: |
| 1154 | comments[:0] = [comment] |
| 1155 | end = end - 1 |
| 1156 | if end < 0: break |
| 1157 | comment = lines[end].expandtabs().lstrip() |
| 1158 | while comments and comments[0].strip() == '#': |
| 1159 | comments[:1] = [] |
| 1160 | while comments and comments[-1].strip() == '#': |
| 1161 | comments[-1:] = [] |
| 1162 | return ''.join(comments) |
| 1163 | |
| 1164 | class EndOfBlock(Exception): pass |
| 1165 |
nothing calls this directly
no test coverage detected