Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates to fix-mutable-params codemod #141

Merged
merged 3 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/core_codemods/fix_mutable_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,25 @@ def __init__(self, *args, **kwargs):
self._matches_builtin = m.Call(func=m.Name("list") | m.Name("dict"))

def _create_annotation(self, orig: cst.Param, updated: cst.Param):
match orig.annotation:
case cst.Annotation(annotation=cst.Subscript(sub)):
match sub: # type: ignore
case cst.Name("Optional"):
# Already an Optional, so we can just preserve the original annotation
return updated.annotation

return (
updated.annotation.with_changes(
annotation=cst.Subscript(
value=cst.Name("Optional"),
slice=[
cst.SubscriptElement(
slice=cst.Index(value=orig.annotation.annotation)
slice=cst.Index(value=updated.annotation.annotation)
)
],
)
)
if updated.annotation is not None
if orig.annotation is not None and updated.annotation is not None
else None
)

Expand Down Expand Up @@ -133,6 +140,14 @@ def _build_new_body(self, new_var_decls, body):
new_body.extend(body[offset:])
return new_body

def _is_abstractmethod(self, node: cst.FunctionDef) -> bool:
for decorator in node.decorators:
match decorator.decorator:
case cst.Name("abstractmethod"):
Copy link
Member Author

Choose a reason for hiding this comment

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

Could possibly be more accurate and guarantee this is imported from abc, but it's probably pretty reliable as-is.

return True

return False

def leave_FunctionDef(
self,
original_node: cst.FunctionDef,
Expand All @@ -144,7 +159,11 @@ def leave_FunctionDef(
new_var_decls,
add_annotation,
) = self._gather_and_update_params(original_node, updated_node)
new_body = self._build_new_body(new_var_decls, updated_node.body.body)
new_body = (
self._build_new_body(new_var_decls, updated_node.body.body)
if not self._is_abstractmethod(original_node)
else updated_node.body.body
)
if new_var_decls:
# If we're adding statements to the body, we know a change took place
self.add_change(original_node, self.CHANGE_DESCRIPTION)
Expand Down
Loading
Loading