Skip to content

Instantly share code, notes, and snippets.

@pcorpet
Created June 20, 2023 05:27
Show Gist options
  • Save pcorpet/6f10fc8a0a69ab25653c251b8174f1bc to your computer and use it in GitHub Desktop.
Save pcorpet/6f10fc8a0a69ab25653c251b8174f1bc to your computer and use it in GitHub Desktop.
Converts all python files to use dict literals instead of a function.
import libcst as cst
import os
def process_file(file_path):
# Read the content of the file
with open(file_path, "r") as file:
code = file.read()
# Parse the code file into a CST
cst_tree = cst.parse_module(code)
# Define a CST transformer to replace dict calls with {}
class DictToBracesTransformer(cst.CSTTransformer):
is_modified = False
def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.Call:
if not isinstance(updated_node.func, cst.Name) or updated_node.func.value != "dict":
return updated_node
if len(updated_node.args) == 1 and not updated_node.args[0].keyword:
# dict(another_var)
return updated_node
self.is_modified = True
return cst.Dict(
elements=[
self._convert_arg(arg, updated_node)
for arg in updated_node.args
],
lbrace=cst.LeftCurlyBrace(whitespace_after=updated_node.whitespace_before_args)
)
def _convert_arg(self, updated_arg: cst.Arg, call_node: cst.Call) -> cst.DictElement:
if updated_arg.keyword and updated_arg.value and isinstance(updated_arg.keyword, cst.Name):
return cst.DictElement(
key=cst.SimpleString(value=f'"{updated_arg.keyword.value}"'),
value=updated_arg.value,
comma=updated_arg.comma)
breakpoint()
# Create an instance of the transformer
transformer = DictToBracesTransformer()
# Transform the CST and get the modified CST
new_cst_tree = cst_tree.visit(transformer)
if not transformer.is_modified:
return
# Convert the modified CST back to code while preserving comments
modified_code = new_cst_tree.code
# Write the modified code back to the file
with open(file_path, "w") as file:
file.write(modified_code)
# Specify the folder path
folder_path = "./"
# Process each Python file in the folder
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".py"):
file_path = os.path.join(root, file)
process_file(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment