Instagram / Instagram/LibCST

@leave decorator matches against original node, not updated node

Open
#399 0 comments 0 reactions 0 assignees View on GitHub
machinery
Dominant language
Python
Stars
1.9k
Forks
229
PR merge metrics
No merged PRs in 30d

Description

Thanks for the really useful library!

I was expecting the `@leave` decorator to match against the version of the node that has already been transformed by deeper-nested leave functions, but it doesn't seem to. I'm not sure if this is a bug, or whether it is intentional and should be clarified in the documentation.

The example where I thought this would be useful is to allow the second, neater version:

```python
import libcst as cst
import libcst.matchers as m

test_code = """
x = 2 # A deleteme comment
y = 3 # deleteme
z = 6
"""

class TransformerWorks(m.MatcherDecoratableTransformer):
def leave_Comment(self, original_node, updated_node):
return updated_node.with_changes(
value=updated_node.value.replace("deleteme", "")
)

# This works
@m.leave(m.TrailingWhitespace(comment=m.Comment()))
def remove_empty_comments(self, original_node, updated_node):
"""Remove comments that are now empty, i.e. contain only ' ' and '#'."""
if updated_node.comment.value.strip(" #") == "":
updated_node = updated_node.with_changes(
whitespace=cst.SimpleWhitespace(""), comment=None
)
return updated_node

class TransformerDoesNotWork(m.MatcherDecoratableTransformer):
def leave_Comment(self, original_node, updated_node):
return updated_node.with_changes(
value=updated_node.value.replace("deleteme", "")
)

@m.leave(m.TrailingWhitespace(comment=m.Comment(value=m.MatchRegex("^[ #]*$"))))
def remove_empty_comments(self, original_node, updated_node):
"""Remove comments that are now empty, i.e. contain only ' ' and '#'."""
return updated_node.with_changes(
whitespace=cst.SimpleWhitespace(""), comment=None
)

tree = cst.parse_module(test_code)
print("This works:")
print(tree.visit(TransformerWorks()).code)
print()
print("This doesn't work:")
print(tree.visit(TransformerDoesNotWork()).code)
```

This prints

```
This works:

x = 2 # A comment
y = 3
z = 6

This doesn't work:

x = 2 # A comment
y = 3 #
z = 6
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.