Comment Parser

1.2.5 · active · verified Thu Apr 16

comment-parser is a Python module designed to extract comments from various source code files. It supports common languages like C, C++, Java, JavaScript, Python, and others, handling both single-line and multi-line comment formats. The library, currently at version 1.2.5, features an active release schedule, with recent updates focusing on setup stability and adding typing information.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to extract comments from both a string and a temporary file. It uses `extract_comments_from_str` and `extract_comments` by explicitly specifying the MIME type for the code, which is recommended for reliable parsing across different languages. The output for each comment includes its text, line number, and whether it's a multi-line comment.

import os
import tempfile
from comment_parser import comment_parser

# Example 1: Extract comments from a string
python_code = """
# This is a single-line Python comment
def example_function():
    '''
    This is a docstring, not a comment parsed by comment-parser by default.
    '''
    x = 10  # Inline comment

# Another line
"""

try:
    # Explicitly specify MIME type for robust parsing
    comments_from_str = comment_parser.extract_comments_from_str(python_code, mime='text/x-python')
    print("\n--- Comments from string ---")
    for comment in comments_from_str:
        print(f"[Line {comment.line_number}] {comment.text} (Multiline: {comment.is_multiline})")
except Exception as e:
    print(f"Error parsing string: {e}")

# Example 2: Extract comments from a file
# Create a dummy file for demonstration
temp_dir = tempfile.gettempdir()
file_path = os.path.join(temp_dir, 'example.c')

c_code = """
/* This is a multi-line C comment
 * spanning several lines. */
#include <stdio.h>

// Single line C comment
int main() {
    printf("Hello, World!");
    return 0;
}
"""

with open(file_path, 'w') as f:
    f.write(c_code)

try:
    # Using extract_comments with a file path
    comments_from_file = comment_parser.extract_comments(file_path, mime='text/x-c')
    print("\n--- Comments from file ---")
    for comment in comments_from_file:
        print(f"[Line {comment.line_number}] {comment.text} (Multiline: {comment.is_multiline})")
except Exception as e:
    print(f"Error parsing file: {e}")
finally:
    # Clean up the dummy file
    if os.path.exists(file_path):
        os.remove(file_path)

view raw JSON →