Skip to content

Skip unused code for functions#164

Merged
dbasunag merged 4 commits into
mainfrom
skip-unused-code-for-functions
Mar 13, 2025
Merged

Skip unused code for functions#164
dbasunag merged 4 commits into
mainfrom
skip-unused-code-for-functions

Conversation

@myakove
Copy link
Copy Markdown
Collaborator

@myakove myakove commented Mar 12, 2025

Support for skipping function using comment in the code.

For example:

def my_func(): # skip-unused-code
    pass

Summary by CodeRabbit

  • Documentation
    • Updated guidance with new sections and clearer instructions for configuring exclusions.
  • New Features
    • Enhanced the tool to allow skipping individual function checks via inline annotations.
    • Improved detection accuracy for function usage.
  • Tests
    • Expanded test coverage to ensure the new exclusion features and improved analysis work as expected.
  • Chores
    • Added a new dependency to the project requirements.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 12, 2025

Walkthrough

This pull request updates the documentation, the core processing logic, and the test suite for the unused code detection tool. The documentation now includes additional sections to clarify usage and configuration, including a method to skip individual functions via inline comments. In the core module, the AST parsing method has been updated and a condition added to bypass functions marked with a skip comment. The tests have been expanded to verify the new skip functionality. No changes were made to any exported or public entities.

Changes

File(s) Change Summary
apps/unused_code/README.md Added sections explaining tool usage, YAML configuration, and a new subsection for skipping single functions using # skip-unused-code.
apps/unused_code/unused_code.py Replaced ast.parse with ast_comments.parse, added a conditional check to skip functions containing # skip-unused-code, and improved regex usage for function call detection.
tests/unused_code/test_unused_code.py Introduced a new test to verify the skip comment functionality.
tests/unused_code/unused_code_file_for_test.py Added a helper function (skip_with_comment) to simulate the skip behavior during tests.
pyproject.toml Added a new dependency: "ast-comments>=1.2.2".

Suggested labels

verified, size/L, can-be-merged, approved-myakove

Suggested reviewers

  • rnetser

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82cc9b1 and 0400293.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • pyproject.toml (1 hunks)
  • tests/unused_code/test_unused_code.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unused_code/test_unused_code.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (1)
pyproject.toml (1)

19-20: New Dependency Addition: ast-comments>=1.2.2

The added dependency supports the updated AST parsing functionality (to handle function skip comments) in the unused_code module. Please confirm that this version has been tested for compatibility with the rest of the codebase.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@rh-bot-1
Copy link
Copy Markdown

Report bugs in Issues

The following are automatically added:

  • Add reviewers from OWNER file (in the root of the repository) under reviewers section.
  • Set PR size label.
  • New issue is created for the PR. (Closed when PR is merged/closed)
  • Run pre-commit if .pre-commit-config.yaml exists in the repo.

Available user actions:

  • To mark PR as WIP comment /wip to the PR, To remove it from the PR comment /wip cancel to the PR.
  • To block merging of PR comment /hold, To un-block merging of PR comment /hold cancel.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To cherry pick a merged PR comment /cherry-pick <target branch to cherry-pick to> in the PR.
    • Multiple target branches can be cherry-picked, separated by spaces. (/cherry-pick branch1 branch2)
    • Cherry-pick will be started when PR is merged
  • To build and push container image command /build-and-push-container in the PR (tag will be the PR number).
    • You can add extra args to the Podman build command
      • Example: /build-and-push-container --build-arg OPENSHIFT_PYTHON_WRAPPER_COMMIT=<commit_hash>
  • To add a label by comment use /<label name>, to remove, use /<label name> cancel
  • To assign reviewers based on OWNERS file use /assign-reviewers
  • To check if PR can be merged use /check-can-merge
  • to assign reviewer to PR use /assign-reviewer @<reviewer>
Supported /retest check runs
  • /retest tox: Retest tox
  • /retest python-module-install: Retest python-module-install
  • /retest all: Retest all
Supported labels
  • hold
  • verified
  • wip
  • lgtm

rnetser
rnetser previously approved these changes Mar 12, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f76d48 and 82cc9b1.

📒 Files selected for processing (4)
  • apps/unused_code/README.md (3 hunks)
  • apps/unused_code/unused_code.py (3 hunks)
  • tests/unused_code/test_unused_code.py (1 hunks)
  • tests/unused_code/unused_code_file_for_test.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (6)
tests/unused_code/unused_code_file_for_test.py (1)

9-10: Implementation aligns with PR objectives

The addition of skip_with_comment() function with the # skip-unused-code comment serves as a perfect test case for the new feature being introduced in this PR. This allows developers to mark certain functions to be skipped during unused code detection.

apps/unused_code/README.md (2)

40-48: Clear documentation of the new feature

The documentation clearly explains how to use the new # skip-unused-code comment feature with a good example. This will help users understand and adopt the feature.


17-25: Improved YAML formatting enhances readability

The indentation changes in the YAML example improve consistency and readability of the configuration example.

apps/unused_code/unused_code.py (3)

62-62: AST parsing method updated to support comments

The change from ast.parse to parse from the ast_comments module is appropriate for the feature, as it enables access to comments which are ignored by the standard AST parser.


78-78: Improved regex for function call detection

Changing from -w to -wE in the git grep command improves the pattern matching by treating the pattern as an extended regular expression. This allows for more precise detection of function calls with arguments.


73-75:

Details

❓ Verification inconclusive

New feature implementation to skip functions

This code correctly implements the feature to skip functions marked with the # skip-unused-code comment. The logic checks if any item in the function body has this specific comment value.

However, it's worth noting that the implementation assumes the comment will be on a separate line within the function body, rather than inline with the function definition as shown in the README example.

Let's verify if inline comments (as shown in README) will work with this implementation:


🏁 Script executed:

#!/bin/bash
# Create a test file with an inline comment
cat << 'EOF' > /tmp/test_inline_comment.py
def my_function(): # skip-unused-code
    pass
EOF

# Check how ast_comments parses this file
python3 -c "from ast_comments import parse; import ast; tree = parse(open('/tmp/test_inline_comment.py').read()); print([item.value for item in tree.body[0].body if hasattr(item, 'value')])"

Length of output: 336


Inline Comment Handling Requires Further Verification

The new feature correctly skips functions when the # skip-unused-code comment is placed on a separate line within the function body. However, the test for inline comments (e.g., def my_function(): # skip-unused-code) resulted in a ModuleNotFoundError for the ast_comments module, leaving its behavior unverified. Please manually verify inline comment handling (or update the test environment to include ast_comments) to confirm it meets the README example expectations.

  • File: apps/unused_code/unused_code.py (Lines 73–75)
  • Issue: Inline comment parsing is unverified due to missing module in the test environment.

Comment thread tests/unused_code/test_unused_code.py Outdated
Comment thread apps/unused_code/unused_code.py
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/unused_code/test_unused_code.py (1)

37-41: Consider clarifying the purpose of this test

This test appears very similar to test_unused_code_function_list_exclude_all() on lines 23-27. Both tests:

  1. Call the same command with identical arguments
  2. Assert the same expected results

While I understand this test is likely validating the new skip-with-comment functionality, the test name and assertions don't make this explicit. Consider either:

  1. Renaming the test to clarify its purpose (e.g., test_skip_with_comment_functionality)
  2. Adding a comment explaining how this test differs from the existing one
  3. Adding more specific assertions to validate the comment-based skipping
-def test_unused_code_check_skip_with_comment():
+def test_skip_with_comment_functionality():
     result = get_cli_runner().invoke(get_unused_functions, '--exclude-function-prefixes "unused_code_"')
     LOGGER.info(f"Result output: {result.output}, exit code: {result.exit_code}, exceptions: {result.exception}")
     assert result.exit_code == 0
-    assert "Is not used anywhere in the code" not in result.output
+    # Verify that skip_with_comment function isn't flagged as unused
+    assert "skip_with_comment" not in result.output
+    assert "Is not used anywhere in the code" not in result.output
apps/unused_code/unused_code.py (1)

73-75: Consider making the comment detection more flexible

The current implementation looks for an exact match of # skip-unused-code. You might want to consider making this more flexible by:

  1. Allowing different spacing (e.g., #skip-unused-code or # skip-unused-code )
  2. Making it case-insensitive
  3. Supporting placing the comment on a different line (e.g., as a docstring)
-        if any(getattr(item, "value", None) == "# skip-unused-code" for item in func.body):
+        skip_pattern = "skip-unused-code"
+        if any(getattr(item, "value", None) and skip_pattern in getattr(item, "value", "").lower().strip() for item in func.body):
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f76d48 and 82cc9b1.

📒 Files selected for processing (4)
  • apps/unused_code/README.md (3 hunks)
  • apps/unused_code/unused_code.py (3 hunks)
  • tests/unused_code/test_unused_code.py (1 hunks)
  • tests/unused_code/unused_code_file_for_test.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (7)
tests/unused_code/unused_code_file_for_test.py (1)

9-10: LGTM: Good test function for the new skip feature

The addition of this function with the # skip-unused-code comment provides a good test case for verifying the new feature's functionality.

apps/unused_code/README.md (1)

41-48: LGTM: Clear documentation for the new feature

The documentation clearly explains how to use the new skip comment functionality with a good example.

apps/unused_code/unused_code.py (5)

12-12: LGTM: Added necessary import for comment parsing

The addition of the ast_comments import is essential for the new feature that needs to parse code comments.


62-62: LGTM: Updated parsing to support comments

Switching from standard AST parsing to the ast_comments.parse function enables handling of comments in the code, which is necessary for the new skip functionality.


73-75: LGTM: Well-implemented comment detection

The implementation efficiently checks for the presence of the skip comment in the function body using a generator expression.


78-78: Enhanced git grep pattern for better function detection

The updated git grep command with -wE flags and function argument pattern improves function usage detection:

  • -w ensures whole word matching (prevents partial matches)
  • -E enables extended regex for the function call pattern
  • The pattern {func.name}(.*) matches function calls with arguments

77-78:

Details

✅ Verification successful

Verify that the new grep pattern doesn't miss any legitimate function calls

The change from the previous grep command to using -wE with a pattern that includes function arguments is a significant change that could affect how function usages are detected.


🏁 Script executed:

#!/bin/bash
# Compare the results of the old and new grep patterns to ensure we don't miss any legitimate function calls

# First, find a function name we can test with
FUNC_NAME=$(grep -r "def " --include="*.py" . | head -1 | sed 's/.*def \([a-zA-Z0-9_]*\).*/\1/')

echo "Testing with function: $FUNC_NAME"

# Compare old style (without -wE and function args pattern) vs new style
echo "Old style grep:"
git grep "$FUNC_NAME" | grep -v "def $FUNC_NAME"

echo "New style grep:"
git grep -wE "$FUNC_NAME(.*)" | grep -v "def $FUNC_NAME"

# Check if any results differ
DIFF_COUNT=$(diff <(git grep "$FUNC_NAME" | grep -v "def $FUNC_NAME") <(git grep -wE "$FUNC_NAME(.*)" | grep -v "def $FUNC_NAME") | wc -l)
echo "Number of differences: $DIFF_COUNT"

if [ $DIFF_COUNT -gt 0 ]; then
  echo "Warning: The new grep pattern may miss some function calls"
  diff <(git grep "$FUNC_NAME" | grep -v "def $FUNC_NAME") <(git grep -wE "$FUNC_NAME(.*)" | grep -v "def $FUNC_NAME")
fi

Length of output: 1406


Grep Pattern Verification Confirmed: No Missed Function Calls Detected
The verification script shows that the updated grep pattern (-wE with the function arguments pattern) produces the same results as the old grep command. In the test run using the function get_issue, there were no differences identified (diff count of 0), confirming that all legitimate function calls are being correctly detected.

  • Location: apps/unused_code/unused_code.py, Lines 77-78

Great work on this change—no further adjustments are required here.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/unused_code/test_unused_code.py (1)

37-41: Test might not be specifically testing the skip comment feature

This test appears to be duplicating the functionality of test_unused_code_function_list_exclude_all() (lines 23-27). Both tests use the same --exclude-function-prefixes "unused_code_" parameter and have identical assertions. Consider modifying this test to specifically verify the comment-based skipping feature rather than function prefix exclusion.

-def test_unused_code_check_skip_with_comment():
-    result = get_cli_runner().invoke(get_unused_functions, '--exclude-function-prefixes "unused_code_"')
+def test_unused_code_check_skip_with_comment():
+    # Test that functions with '# skip-unused-code' comment are skipped without using exclusion prefixes
+    result = get_cli_runner().invoke(get_unused_functions)
     LOGGER.info(f"Result output: {result.output}, exit code: {result.exit_code}, exceptions: {result.exception}")
     assert result.exit_code == 0
     assert "Is not used anywhere in the code" not in result.output
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f76d48 and 82cc9b1.

📒 Files selected for processing (4)
  • apps/unused_code/README.md (3 hunks)
  • apps/unused_code/unused_code.py (3 hunks)
  • tests/unused_code/test_unused_code.py (1 hunks)
  • tests/unused_code/unused_code_file_for_test.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (6)
tests/unused_code/unused_code_file_for_test.py (1)

9-10: Great implementation of the skippable function with comment!

The function skip_with_comment() correctly demonstrates how to use the new # skip-unused-code comment to mark a function that should be excluded from unused code checks.

apps/unused_code/README.md (1)

41-48: Clear documentation for the new skip feature!

The documentation for skipping a single function using the # skip-unused-code comment is clear and includes a helpful example. This will make it easy for users to understand how to use this new feature.

apps/unused_code/unused_code.py (4)

12-12: Good addition of the ast_comments parser

Using the ast_comments parser is essential for the new skip comment feature as it preserves comments that would be otherwise lost with the standard AST parser.


62-62: Correct implementation of the ast_comments parser

Using parse from the ast_comments module instead of ast.parse enables the feature to detect and process comments in the code.


78-78: Improved function usage detection

Using the -wE flags with the enhanced regex pattern {func.name}(.*) will better match function calls with different parameter patterns, reducing false negatives in the detection.


73-75:

Details

✅ Verification successful

Verify comment detection implementation

The implementation checks for the # skip-unused-code comment in the function body, but the example in the README shows the comment on the function definition line. This might lead to inconsistent behavior.

Let's verify how the ast_comments parser represents comments that appear at the end of a function definition line:


🏁 Script executed:

#!/bin/bash
# Create a test file with different comment placements
cat > test_comments.py << 'EOF'
def function_with_comment_on_def_line():  # skip-unused-code
    pass

def function_with_comment_in_body():
    # skip-unused-code
    pass
EOF

# Install ast-comments if not already installed
pip install ast-comments > /dev/null 2>&1

# Create a script to parse and inspect the AST
cat > inspect_ast.py << 'EOF'
from ast_comments import parse

with open('test_comments.py', 'r') as file:
    tree = parse(source=file.read())

for node in tree.body:
    if hasattr(node, 'name'):
        print(f"Function: {node.name}")
        print(f"  Body items: {len(node.body)}")
        for item in node.body:
            if hasattr(item, 'value'):
                print(f"  - Item value: {repr(item.value)}")
EOF

# Run the inspection script
python inspect_ast.py

Length of output: 252


Consistent Comment Detection Verified

The test results confirm that regardless of whether the # skip-unused-code comment is placed on the function definition line or within the function body, the ast-comments parser represents it as a body item with the same value. This shows that the current implementation—which checks for the comment in the function’s body—is consistent with the behavior described in the README.

No code changes are required.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/unused_code/test_unused_code.py (1)

37-41: Consider whether this duplicate test is necessary.

This test appears to be functionally identical to the existing test_unused_code_function_list_exclude_all() on lines 23-27. Both tests:

  1. Run the same command with the same parameters (--exclude-function-prefixes "unused_code_")
  2. Assert the same conditions (exit code 0 and absence of "not used" message)

If the purpose is to specifically test the new skip comment functionality, consider either:

  1. Removing the duplicate test and modifying the test case name to reflect both exclusion methods
  2. Making this test more focused on the skip comment feature by using different parameters
-def test_unused_code_check_skip_with_comment():
-    result = get_cli_runner().invoke(get_unused_functions, '--exclude-function-prefixes "unused_code_"')
+def test_unused_code_check_skip_with_comment():
+    # Test specifically for the skip-unused-code comment functionality
+    result = get_cli_runner().invoke(get_unused_functions)
     LOGGER.info(f"Result output: {result.output}, exit code: {result.exit_code}, exceptions: {result.exception}")
     assert result.exit_code == 0
     assert "Is not used anywhere in the code" not in result.output
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f76d48 and 82cc9b1.

📒 Files selected for processing (4)
  • apps/unused_code/README.md (3 hunks)
  • apps/unused_code/unused_code.py (3 hunks)
  • tests/unused_code/test_unused_code.py (1 hunks)
  • tests/unused_code/unused_code_file_for_test.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (7)
tests/unused_code/unused_code_file_for_test.py (1)

7-10: LGTM! Example function added for testing the skip comment feature.

The new skip_with_comment() function correctly implements the skip-unused-code comment pattern and will serve as a good test case for verifying that functions with this comment are properly excluded from unused code checks.

apps/unused_code/README.md (1)

40-48: LGTM! Clear documentation for the new feature.

The added section clearly explains how to skip a single function in a file by adding the # skip-unused-code comment. The example is concise and demonstrates the correct syntax. Good documentation practice!

apps/unused_code/unused_code.py (5)

12-12: LGTM! Added required dependency for comment parsing.

The import of parse from the ast_comments module is necessary to handle the new comment-based functionality.


62-62: LGTM! Replaced standard AST parser with comment-aware parser.

Using parse from ast_comments instead of ast.parse is necessary as the standard AST parser doesn't preserve comments. This change enables the skip-unused-code feature to work.


73-76: LGTM! Core implementation of the skip-unused-code feature.

The added condition correctly checks for the presence of the "# skip-unused-code" comment in the function body and skips processing if found. The debug log message provides useful information for troubleshooting.


78-78: Improved function usage detection with better regex pattern.

The grep command has been improved to use word boundaries (-w) and extended regex (-E), which will provide more accurate function usage detection and reduce false positives.


73-78:

Details

❓ Verification inconclusive

Verify if comments in function body are properly detected.

The implementation checks for the comment in func.body, but the documentation and example suggest placing the comment at the function definition line. Make sure the AST parser correctly captures comments placed at the function signature line.


🏁 Script executed:

#!/bin/bash
# Create a temporary test file with different comment placements
cat > test_comment_detection.py << 'EOL'
def function_with_comment_after_def():  # skip-unused-code
    pass

def function_with_comment_in_body():
    # skip-unused-code
    pass
EOL

# Use the ast_comments parser to inspect the AST
python3 -c "
from ast_comments import parse
with open('test_comment_detection.py', 'r') as f:
    tree = parse(source=f.read())

print('== Function 1 ==')
for item in tree.body[0].body:
    print(f'Body item value: {getattr(item, \"value\", None)}')

print('\\n== Checking Function 1 with condition ==')
print(f'Would be skipped: {any(getattr(item, \"value\", None) == \"# skip-unused-code\" for item in tree.body[0].body)}')

print('\\n== Function 2 ==')
for item in tree.body[1].body:
    print(f'Body item value: {getattr(item, \"value\", None)}')

print('\\n== Checking Function 2 with condition ==')
print(f'Would be skipped: {any(getattr(item, \"value\", None) == \"# skip-unused-code\" for item in tree.body[1].body)}')
"

# Clean up
rm test_comment_detection.py

Length of output: 938


Action Required: Verify AST Comment Detection on Function Signatures

The automated test using the ast_comments module failed with a ModuleNotFoundError. This prevents us from confirming that comments placed on the function definition line (inline comments) are properly captured. As the current logic only inspects func.body, there’s still uncertainty whether inline comments (e.g., def foo(): # skip-unused-code) would be detected correctly per the documentation.

• Please manually verify that the AST parser (or the alternative method used for comment detection) correctly identifies the # skip-unused-code comment when it’s placed on the function signature line.
• If needed, adjust the logic to inspect both the function signature and its body.

Comment thread apps/unused_code/unused_code.py
Comment thread tests/unused_code/test_unused_code.py Outdated
Comment thread pyproject.toml
@myakove
Copy link
Copy Markdown
Collaborator Author

myakove commented Mar 13, 2025

/verified

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants