Skip to content

Commit

Permalink
Add new style of "if" statements
Browse files Browse the repository at this point in the history
  • Loading branch information
yunline committed Dec 11, 2024
1 parent 01bbb02 commit 2b0c5b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
5 changes: 5 additions & 0 deletions oneliner/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,9 @@ class Configs:
"chain_call",
"Choose the expr_wrapper",
)
if_style = Cfg(
["if_expr", "short_circuit"],
"if_expr",
"Choose the style of the convertion of 'if' statements",
)
config_names = tuple(name for name in locals() if not name.startswith("__"))
19 changes: 12 additions & 7 deletions oneliner/pending_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,18 @@ def __init__(self, node: If, nsp: Namespace, nsp_global: NamespaceGlobal):
self.converted_orelse = []

def get_result(self) -> list[expr]:
return [
IfExp(
test=expr_transf(self.nsp, self.node.test),
body=self.nsp_global.expr_wraper(self.converted_body),
orelse=self.nsp_global.expr_wraper(self.converted_orelse),
)
]
test = expr_transf(self.nsp, self.node.test)
body = self.nsp_global.expr_wraper(self.converted_body)
orelse = self.nsp_global.expr_wraper(self.converted_orelse)
if self.nsp_global.configs.if_style == "short_circuit":
if len(self.converted_orelse)>0:
body_or_true = BoolOp(op=Or(), values=[body, Constant(value=1)])
semi_if = BoolOp(op=And(), values=[test, body_or_true])
return [BoolOp(op=Or(),values=[semi_if, orelse])]
else:
return [BoolOp(op=And(), values=[test, body])]
else: # if_style=="if_expr"
return [IfExp(test=test, body=body, orelse=orelse)]

def _iter_nodes(self) -> typing.Generator[AST, list[expr], None]:
if self.nsp.loop_stack:
Expand Down

0 comments on commit 2b0c5b5

Please sign in to comment.