Skip to content

Flatten syntactically nested Union or Literal instances #40

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

Merged
merged 8 commits into from
May 12, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
52 changes: 52 additions & 0 deletions src/shed/_codemods.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,55 @@ def _has_none(node):
return updated_node.with_changes(left=updated_node.right, right=node_left)
else:
return updated_node

@m.call_if_inside(m.Annotation(annotation=m.BinaryOperation()))
@m.leave(
m.BinaryOperation(
left=m.Subscript(value=m.Name(value="Literal")),
operator=m.BitOr(),
right=m.Name("None"),
)
)
def flatten_literal(self, _, updated_node):
left_node = updated_node.left
args = list(left_node.slice)
args[-1] = args[-1].with_changes(
comma=cst.Comma(
whitespace_before=cst.SimpleWhitespace(
value="",
),
whitespace_after=cst.SimpleWhitespace(
value=" ",
),
)
)
args.append(
cst.SubscriptElement(
slice=cst.Index(value=cst.Name(value="None")),
comma=cst.MaybeSentinel.DEFAULT,
)
)
left_node = left_node.with_changes(slice=tuple(args))
return left_node

@m.leave(m.Subscript(value=m.Name(value="Union")))
def flatten_union(self, _, updated_node):
new_slice = []
has_none = False
for item in updated_node.slice:
if m.matches(item.slice.value, m.Subscript(m.Name("Optional"))):
new_slice.append(
item.with_changes(slice=item.slice.value.slice[0].slice)
) # peel off "Optional"
has_none = True
else:
new_slice.append(item)
if has_none:
new_slice.append(
cst.SubscriptElement(
slice=cst.Index(value=cst.Name(value="None")),
comma=cst.MaybeSentinel.DEFAULT,
)
)
return updated_node.with_changes(slice=new_slice)
return updated_node # nothing changes
7 changes: 7 additions & 0 deletions tests/recorded/flatten_literal.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Literal[1, 2] | None # this should not change
var: Literal[1, 2] | None

================================================================================

Literal[1, 2] | None # this should not change
var: Literal[1, 2, None]
5 changes: 5 additions & 0 deletions tests/recorded/flatten_union.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Union[int, Optional[str], bool]

================================================================================

Union[int, str, bool, None]