Skip to content

Commit ce0fc98

Browse files
Bela Stoyanpavelzw
Bela Stoyan
andauthored
generalize transformer to also handle partial returns (#11)
Co-authored-by: Pavel Zwerschke <[email protected]>
1 parent 9de864a commit ce0fc98

File tree

7 files changed

+219
-155
lines changed

7 files changed

+219
-155
lines changed

README.md

+33
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ This gets transformed into:
4242
def signum(x: pl.Expr) -> pl.Expr:
4343
return pl.when(x > 0).then(1).otherwise(pl.when(x < 0).then(-1).otherwise(0))
4444
```
45+
4546
### Handling Multiple Statements
4647

4748
polarIFy can also handle multiple statements like:
@@ -125,6 +126,38 @@ print(result)
125126
# └─────┴─────────┘
126127
```
127128

129+
### Displaying the transpiled polars expression
130+
131+
You can also display the transpiled polars expression by calling the `transform_func_to_new_source` method:
132+
133+
```python
134+
from polarify import transform_func_to_new_source
135+
136+
def signum(x):
137+
s = 0
138+
if x > 0:
139+
s = 1
140+
elif x < 0:
141+
s = -1
142+
return s
143+
144+
145+
print(f"Original function:\n{inspect.getsource(signum)}")
146+
# Original function:
147+
# def signum(x):
148+
# s = 0
149+
# if x > 0:
150+
# s = 1
151+
# elif x < 0:
152+
# s = -1
153+
# return s
154+
print(f"Transformed function:\n{transform_func_to_new_source(signum)}")
155+
# Transformed function:
156+
# def signum_polarified(x):
157+
# import polars as pl
158+
# return pl.when(x > 0).then(1).otherwise(pl.when(x < 0).then(-1).otherwise(0))
159+
```
160+
128161
TODO: complicated example with nested functions
129162

130163
## ⚙️ How It Works

pixi.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# https://github.com/prefix-dev/pixi/issues/79
33
[project]
44
name = "polarify"
5-
version = "0.1.1"
5+
version = "0.1.2"
66
description = "Simplifying conditional Polars Expressions with Python 🐍 🐻‍❄️"
77
authors = ["Bela Stoyan <[email protected]>", "Pavel Zwerschke <[email protected]>"]
88
channels = ["conda-forge"]

polarify/__init__.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@
22
import inspect
33
from functools import wraps
44

5-
from .main import parse_body
5+
from .main import parse_body, transform_tree_into_expr
66

77

88
def transform_func_to_new_source(func) -> str:
99
source = inspect.getsource(func)
1010
tree = ast.parse(source)
1111
func_def: ast.FunctionDef = tree.body[0] # type: ignore
12-
expr = parse_body(func_def.body)
12+
root_node = parse_body(func_def.body)
13+
14+
expr = transform_tree_into_expr(root_node)
1315

1416
# Replace the body of the function with the parsed expr
1517
# Also import polars as pl since this is used in the generated code

0 commit comments

Comments
 (0)