diff options
author | Georg Brandl <georg@python.org> | 2006-10-12 09:20:33 (GMT) |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2006-10-12 09:20:33 (GMT) |
commit | b2e81e307dc7e7d8a552619b6defddb06e028613 (patch) | |
tree | 10febe68a3f2d998257a24883cc1c36808df5383 /Lib/inspect.py | |
parent | a4c8e32a1f1a1eb4014a9f289360e241f942455a (diff) | |
download | cpython-b2e81e307dc7e7d8a552619b6defddb06e028613.zip cpython-b2e81e307dc7e7d8a552619b6defddb06e028613.tar.gz cpython-b2e81e307dc7e7d8a552619b6defddb06e028613.tar.bz2 |
Bug #1550524: better heuristics to find correct class definition
in inspect.findsource().
Diffstat (limited to 'Lib/inspect.py')
-rw-r--r-- | Lib/inspect.py | 19 |
1 files changed, 17 insertions, 2 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py index ba2021a..986a415 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -472,9 +472,24 @@ def findsource(object): if isclass(object): name = object.__name__ - pat = re.compile(r'^\s*class\s*' + name + r'\b') + pat = re.compile(r'^(\s*)class\s*' + name + r'\b') + # make some effort to find the best matching class definition: + # use the one with the least indentation, which is the one + # that's most probably not inside a function definition. + candidates = [] for i in range(len(lines)): - if pat.match(lines[i]): return lines, i + match = pat.match(lines[i]) + if match: + # if it's at toplevel, it's already the best one + if lines[i][0] == 'c': + return lines, i + # else add whitespace to candidate list + candidates.append((match.group(1), i)) + if candidates: + # this will sort by whitespace, and by line number, + # less whitespace first + candidates.sort() + return lines, candidates[0][1] else: raise IOError('could not find class definition') |