Grab the slides:
https://slides.com/cheukting_ho/reformating-code
There are so many good reformatter avaliable
or PyBetter or Autoflake or isort or...
Do you want to make one yourself?
fn(1, 2) # calls fn
Source: https://libcst.readthedocs.io/en/latest/why_libcst.html
(They care about those white spaces)
fn(1, 2) # calls fn
Source: https://libcst.readthedocs.io/en/latest/why_libcst.html
(*not all formatters uses LibCST)
LibCST parses Python 3.0 -> 3.11 source code as a CST tree that keeps all formatting details (comments, whitespaces, parentheses, etc). It's useful for building automated refactoring (codemod) applications and linters.
fn(1, 2) # calls fn
Source: https://libcst.readthedocs.io/en/latest/why_libcst.html
import libcst as cst
cst.parse_expression("1 + 2")
BinaryOperation(
left=Integer(
value='1',
lpar=[],
rpar=[],
),
operator=Add(
whitespace_before=SimpleWhitespace(
value=' ',
),
whitespace_after=SimpleWhitespace(
value=' ',
),
),
right=Integer(
value='2',
lpar=[],
rpar=[],
),
lpar=[],
rpar=[],
)
Imagine you are writing a reformatter...
isinstance
def if_there_is_addition(node):
return m.matches(
node,
m.BinaryOperation(
operator=m.Add(),
),
)
on_visit and
on_leave
class CountAdd(cst.CSTVisitor):
def __init__(self):
self.add_count = 0
def visit_Add(self, node):
self.add_count += 1
print(f"counting add number {self.add_count}")
def leave_Add(self, node):
print("bye!")
source = "1 + 2"
module = cst.parse_module(source)
module.visit(CountAdd())
to travel through and modify code
updated_node
class OffByOne(cst.CSTTransformer):
def __init__(self):
pass
def leave_BinaryOperation(self, original_node, updated_node):
if first_addition(original_node):
return updated_node.with_changes(
left=cst.BinaryOperation(
left=cst.Integer(
value='1',
lpar=[],
rpar=[],
),
operator=cst.Add(
whitespace_before=cst.SimpleWhitespace(
value=' ',
),
whitespace_after=cst.SimpleWhitespace(
value=' ',
),
),
right=original_node.left,
lpar=[],
rpar=[],
)
)
else:
return updated_node.with_changes()
code
attributesource = "1 + 2"
module = cst.parse_module(source)
new = module.visit(OffByOne())
print(new.code)
And write your own
https://conference.pyladies.com/