-
Notifications
You must be signed in to change notification settings - Fork 4
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
feat: create WhileExpr class #142
Conversation
this is an initial idea for both whileexpr and whilestmt: @dispatch
def visit(self, node: astx.WhileExpr) -> str:
"""Handle WhileExpr nodes."""
condition = self.visit(node.condition)
body = self.visit(node.body)
return f"[{body} for _ in iter(lambda: {condition}, False)]"
@dispatch
def visit(self, node: astx.WhileStmt) -> str:
"""Handle WhileStmt nodes."""
condition = self.visit(node.condition)
body = self._generate_block(node.body)
return f"while {condition}:\n{body}" this idea is from gpt .. looks promising |
Code for testing the transpiler for WhileStmt: from astx.flows import WhileStmt
from astx.blocks import Block
from astx.variables import VariableAssignment, Variable
from astx.operators import BinaryOp
from astx.base import SourceLocation
from astx.datatypes import LiteralInt32
from astx.transpilers import python as astx2py
# Define a condition: x < 5
x_var = Variable(name="x")
condition = BinaryOp(
op_code="<",
lhs=x_var,
rhs=LiteralInt32(5),
loc=SourceLocation(line=1, col=0)
)
# Define the loop body: x = x + 1
update_expr = VariableAssignment(
name="x",
value=BinaryOp(
op_code="+",
lhs=x_var,
rhs=LiteralInt32(1),
loc=SourceLocation(line=2, col=4)
),
loc=SourceLocation(line=2, col=4)
)
# Create the body block
body_block = Block(name="while_body")
body_block.append(update_expr)
while_stmt = WhileStmt(
condition=condition,
body=body_block,
loc=SourceLocation(line=1, col=0)
)
# Initialize the generator
generator = astx2py.ASTxPythonTranspiler()
# Generate Python code
generated_code = generator.visit(while_stmt)
print(generated_code) Output: while (x < 5):
x = (x + 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm! thanks for working on that @apkrelling
🎉 This PR is included in version 0.16.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
Pull Request description
This PR adds
WhileExpr
and modifiesWhile
->WhileStmt
.This PR is an attempt to resolve #96 .
WhileExpr
class__init__.py
to include the new imports and classes in the__all__
listWhileExpr
WhileStmt
(there weren't any)WhileStmt
andWhileExpr
WhileStmt
andWhileExpr
How to test these changes
Output of
while_expr.__str__()
:WhileExpr[BinaryOp[<](Variable[x],LiteralInt32(5))]
Output of the transpiler:
[ x = (x + 1) for _ in iter(lambda: (x < 5), False)]
Pull Request checklists
This PR is a:
About this PR:
Author's checklist:
complexity.
Additional information