[issue35113] inspect.getsource returns incorrect source for classes when class definition is part of multiline strings

Serhiy Storchaka report at bugs.python.org
Sat Nov 3 14:12:24 EDT 2018


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

Well, now the hardest problem remains.

Sometimes there are more than one place where the class with the same __qualname__ is defined. See for example multiprocessing/heap.py:

if sys.platform == 'win32':
    class Arena(object):
        ...
else:
    class Arena(object):
        ...

It is hard to determine the correct place. But the current code return the first line, while PR 10307 currently returns the last line.

If the current behavior is more desirable, the code needs to stop searching after finding the first candidate. And the simplest way is to use exceptions:

class ClassVisitor(ast.NodeVisitor):
    def visit_ClassDef(self, node):
        ...
        if found:
            raise StopIterator(line_number)
        ...
...
try:
    class_visitor.visit(tree)
except StopIterator as e:
    line_number = e.value
else:
    raise OSError('could not find class definition')

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35113>
_______________________________________


More information about the Python-bugs-list mailing list