Skip to content

Commit e563fcd

Browse files
alukachkylebarrongadomski
authored
Surface Expr.reduce() in Python (#79)
* Surface Expr.reduce() in Python Stumbled my way through this, would appreciate guidance on if there is a more idiomatic way to achieve the pyo3 logic. * Update python/src/lib.rs Co-authored-by: Kyle Barron <[email protected]> * Update cql2.pyi * Add example --------- Co-authored-by: Kyle Barron <[email protected]> Co-authored-by: Pete Gadomski <[email protected]>
1 parent c848839 commit e563fcd

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

cql2.pyi

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,22 @@ class Expr:
8787
bool: True if the expression matches the item, False otherwise
8888
"""
8989

90+
def reduce(self, item: dict[str, Any] | None = None) -> Expr:
91+
"""Reduces this expression against an item.
92+
93+
Args:
94+
item (dict[str, Any] | None): The item to reduce against
95+
96+
Returns:
97+
Expr: The reduced expression
98+
99+
Examples:
100+
>>> from cql2 import Expr
101+
>>> expr = Expr("true AND true").reduce()
102+
>>> expr.to_text()
103+
'true'
104+
"""
105+
90106
def to_json(self) -> dict[str, Any]:
91107
"""Converts this cql2 expression to a cql2-json dictionary.
92108
@@ -128,7 +144,7 @@ class Expr:
128144
['LC82030282019133LGN00']
129145
"""
130146

131-
def __add__(self, other: "Expr") -> "Expr":
147+
def __add__(self, other: Expr) -> Expr:
132148
"""Combines two cql2 expressions using the AND operator.
133149
134150
Args:

python/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,16 @@ impl Expr {
8181
self.0.clone().matches(Some(&value)).map_err(Error::from)
8282
}
8383

84+
#[pyo3(signature = (item=None))]
85+
fn reduce(&self, item: Option<Bound<'_, PyDict>>) -> Result<Expr> {
86+
let value = item.map(|item| pythonize::depythonize(&item)).transpose()?;
87+
self.0
88+
.clone()
89+
.reduce(value.as_ref())
90+
.map(Expr)
91+
.map_err(Error::from)
92+
}
93+
8494
fn to_json<'py>(&self, py: Python<'py>) -> Result<Bound<'py, PyAny>> {
8595
pythonize::pythonize(py, &self.0).map_err(Error::from)
8696
}

0 commit comments

Comments
 (0)