pythonstringunassigned-variable

How to output all unassigned strings in a python file


I have a python file (a script) that looks like this:

script.py

"""
Multiline comment with unique
text pertaining to the Foo class
"""
class Foo():
    pass


"""
Multiline comment with unique
text pertaining to the Bar class
"""
class Bar():
    pass


"""
Multiline comment with unique
text pertaining to the FooBar class
"""
class FooBar():
    pass


def print_comments():
    # NotImplementedError 

Is there some way for print_comments to detect and output all the unassigned strings so I could see this:

Multiline comment with unique text pertaining to the Foo class

Multiline comment with unique text pertaining to the Bar class

Multiline comment with unique text pertaining to the FooBar class


Solution

  • Assuming the formatting you indicated in your question, something like this should do it:

    class Show_Script():
        def construct(self):
            with open(os.path.abspath(__file__)) as f:
                my_lines = f.readlines()
    
            comments = []
            in_comment = 0
    
            for line in my_lines:
                # detected the start of a comment
                if line.strip().startswith('"""') and in_comment == 0:
                    in_comment = 1
                    comments.append('')
                # detected the end of a comment
                elif line.strip().endswith('"""') and in_comment == 1:
                    in_comment = 0
                # the contents of a comment
                elif in_comment == 1:
                    comments[-1] += line
    
            print '\n'.join(comments)