Skip to content

Commit 2e645e7

Browse files
fix string
1 parent d894355 commit 2e645e7

File tree

3 files changed

+36
-20
lines changed

3 files changed

+36
-20
lines changed

.pre-commit-config.yaml

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,3 @@ repos:
1818
rev: 5.0.4
1919
hooks:
2020
- id: flake8
21-
- repo: https://github.com/pre-commit/mirrors-mypy
22-
rev: "v0.982"
23-
hooks:
24-
- id: mypy

python/tests/test.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,3 +346,17 @@ def test_check_fact(self):
346346

347347
# assert egraph.extract("x") == Call("Num", [Lit(Int(1))])
348348
# assert egraph.extract("y") == Var("y")
349+
350+
351+
class TestVariant:
352+
def test_repr(self):
353+
assert repr(Variant("name", [])) == "Variant('name', [], None)"
354+
355+
def test_name(self):
356+
assert Variant("name", []).name == "name"
357+
358+
def test_types(self):
359+
assert Variant("name", ["a", "b"]).types == ["a", "b"]
360+
361+
def test_cost(self):
362+
assert Variant("name", [], cost=1).cost == 1

src/conversions.rs

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,26 @@ fn wrap_error<T>(tp: &str, obj: &'_ PyAny, block: impl FnOnce() -> PyResult<T>)
1818
})
1919
}
2020

21-
// A variant of a constructor
21+
// Take the repr of a Python object
22+
fn repr(py: Python, obj: PyObject) -> PyResult<String> {
23+
obj.call_method(py, "__repr__", (), None)?.extract(py)
24+
}
25+
26+
trait SizedIntoPy: IntoPy<PyObject> + Sized {}
27+
28+
// Create a dataclass-like repr, of the name of the class of the object
29+
// called with the repr of the fields
30+
fn data_repr(py: Python, obj: PyObject, field_names: Vec<&str>) -> PyResult<String> {
31+
let class_name: String = obj
32+
.getattr(py, "__class__")?
33+
.getattr(py, "__name__")?
34+
.extract(py)?;
35+
let field_strings: PyResult<Vec<String>> = field_names
36+
.iter()
37+
.map(|name| obj.getattr(py, *name).and_then(|x| repr(py, x)))
38+
.collect();
39+
Ok(format!("{}({})", class_name, field_strings?.join(", ")))
40+
}
2241

2342
#[pyclass(name = "Variant")]
2443
#[derive(Clone)]
@@ -47,21 +66,8 @@ impl WrappedVariant {
4766
self.0.cost
4867
}
4968

50-
fn __repr__(&self) -> String {
51-
format!(
52-
"Variant(name={}, types=[{}], cost={})",
53-
self.0.name.to_string(),
54-
self.0
55-
.types
56-
.iter()
57-
.map(|x| x.to_string())
58-
.collect::<Vec<_>>()
59-
.join(", "),
60-
match self.0.cost {
61-
Some(x) => x.to_string(),
62-
None => "None".to_string(),
63-
}
64-
)
69+
fn __repr__(slf: PyRef<'_, Self>, py: Python) -> PyResult<String> {
70+
data_repr(py, slf.into_py(py), vec!["name", "types", "cost"])
6571
}
6672

6773
fn __str__(&self) -> String {

0 commit comments

Comments
 (0)