Skip to content

Commit 4441f8d

Browse files
Add refactors for builtin constructors
- Replace builtins with literal values - Replace empty list constructions with [] Completes a couple tasks in Zac-HD#22.
1 parent f3653b2 commit 4441f8d

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

src/shed/_codemods.py

+34
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,40 @@ def remove_pointless_parens_around_call(self, _, updated_node):
176176
except SyntaxError:
177177
return updated_node
178178

179+
@m.leave(
180+
m.Call(func=m.Name("dict"), args=[])
181+
| m.Call(func=m.Name("list"), args=[])
182+
| m.Call(func=m.Name("tuple"), args=[])
183+
)
184+
def replace_builtin_with_literal(self, _, updated_node):
185+
if updated_node.func.value == "dict":
186+
return cst.Dict([])
187+
elif updated_node.func.value == "list":
188+
return cst.List([])
189+
elif updated_node.func.value == "tuple":
190+
return cst.Tuple([])
191+
else:
192+
raise AssertionError("unreachable")
193+
194+
@m.leave(
195+
m.Call(
196+
func=m.Name("list"),
197+
args=[m.Arg(m.Dict([]) | m.List([]) | m.SimpleString() | m.Tuple([]))],
198+
)
199+
)
200+
def replace_builtin_empty_list(self, _, updated_node):
201+
val = updated_node.args[0].value
202+
val_is_empty_seq = (
203+
isinstance(val, (cst.Dict, cst.List, cst.Tuple)) and not val.elements
204+
)
205+
val_is_empty_str = (
206+
isinstance(val, cst.SimpleString) and val.evaluated_value == ""
207+
)
208+
if val_is_empty_seq or val_is_empty_str:
209+
return cst.List([])
210+
else:
211+
return updated_node
212+
179213
# The following methods fix https://pypi.org/project/flake8-comprehensions/
180214

181215
@m.leave(m.Call(func=m.Name("list"), args=[m.Arg(m.GeneratorExp())]))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
list({})
2+
list([])
3+
list("")
4+
list(())
5+
6+
================================================================================
7+
8+
[]
9+
[]
10+
[]
11+
[]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
dict()
2+
list()
3+
tuple()
4+
5+
================================================================================
6+
7+
{}
8+
[]
9+
()

0 commit comments

Comments
 (0)