Skip to content

Commit

Permalink
Bug #1550524: better heuristics to find correct class definition
Browse files Browse the repository at this point in the history
in inspect.findsource().


git-svn-id: http://svn.python.org/projects/python/trunk@52299 6015fed2-1504-0410-9fe1-9d1591cc4771
  • Loading branch information
georg.brandl committed Oct 12, 2006
1 parent a0ae945 commit 37b33fa
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down

0 comments on commit 37b33fa

Please sign in to comment.