Karthikeyan Singaravelan <tir.kar...@gmail.com> added the comment:
I think parsing with regex especially on multiline cases like here is little tricky handling all cases. I find AST module to be a good fit. I tried using a callback where every class definition is taken up and then from that line to rest of the program getblock can be used to get the relevant class definition. This takes care of the cases I have listed and returns the correct source where we can filter out the class we need. Hence findsource can be modified to use ast instead of regex given that regex was introduced in 2006 and changing class syntax in future might need updating this regex. A sample program I tried but this is the first time I am using ast module and there might be better ways to filter the required classes. I will try raising a PR after some discussion to see if any better solution exists and more tests. # foo_ast.py import ast import inspect class MyClassVisitor(ast.NodeVisitor): def __init__(self, lines, *args, **kwargs): self.lines = lines super().__init__(*args, **kwargs) def visit_ClassDef(self, node): print('Found class "%s"' % node.name) print("Source") print(''.join(inspect.getblock(self.lines[node.lineno-1:]))) with open('../backups/bpo35101_1.py') as f: source = f.read() lines = source.splitlines(True) tree = ast.parse(source) MyClassVisitor(lines).visit(tree) $ ./python.exe ../backups/foo_ast.py Found class "Bar" Source class Bar: a = """ class MultilineStringVariable: ... """ Found class "MultilineStringVariable" Source class MultilineStringVariable: def foo(self): pass Found class "MultilineStringComment" Source class MultilineStringComment: def foo(self): pass Found class "NestedClass" Source class NestedClass: a = ''' class Spam: ... ''' Found class "Nested" Source class Nested: class Spam: pass ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue35113> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com