This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author xtreak
Recipients Windson Yang, pablogsal, xtreak
Date 2018-11-02.07:53:07
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1541145187.12.0.788709270274.issue35113@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2018-11-02 07:53:07xtreaksetrecipients: + xtreak, pablogsal, Windson Yang
2018-11-02 07:53:07xtreaksetmessageid: <1541145187.12.0.788709270274.issue35113@psf.upfronthosting.co.za>
2018-11-02 07:53:07xtreaklinkissue35113 messages
2018-11-02 07:53:07xtreakcreate