From 9257a6d85931dccebbe61fcc0509480df3c7d138 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Fern=C3=A1ndez?= Date: Fri, 3 Oct 2025 01:30:18 +0200 Subject: [PATCH 1/5] feat: make LiteralPredicate serializable via internal IcebergBaseModel --- pyiceberg/expressions/__init__.py | 35 +++++++++++++++++++++++++++ tests/expressions/test_expressions.py | 18 ++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index d0824cc315..6834d2d80d 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -35,6 +35,8 @@ from pydantic import Field +from pydantic import Field + from pyiceberg.expressions.literals import ( AboveMax, BelowMin, @@ -750,6 +752,39 @@ def __init__(self, term: Union[str, UnboundTerm[Any]], literal: Union[L, Literal super().__init__(term) self.literal = _to_literal(literal) # pylint: disable=W0621 + # ---- JSON (Pydantic) serialization helpers ---- + + class _LiteralPredicateModel(IcebergBaseModel): + type: str = Field(alias="type") + term: str + value: Any + + def _json_op(self) -> str: + mapping = { + EqualTo: "eq", + NotEqualTo: "not-eq", + LessThan: "lt", + LessThanOrEqual: "lt-eq", + GreaterThan: "gt", + GreaterThanOrEqual: "gt-eq", + StartsWith: "starts-with", + NotStartsWith: "not-starts-with", + } + for cls, op in mapping.items(): + if isinstance(self, cls): + return op + raise ValueError(f"Unknown LiteralPredicate: {type(self).__name__}") + + def model_dump(self, **kwargs: Any) -> dict: + term_name = getattr(self.term, "name", str(self.term)) + return self._LiteralPredicateModel(type=self._json_op(), term=term_name, value=self.literal.value).model_dump(**kwargs) + + def model_dump_json(self, **kwargs: Any) -> str: + term_name = getattr(self.term, "name", str(self.term)) + return self._LiteralPredicateModel(type=self._json_op(), term=term_name, value=self.literal.value).model_dump_json( + **kwargs + ) + def bind(self, schema: Schema, case_sensitive: bool = True) -> BoundLiteralPredicate[L]: bound_term = self.term.bind(schema, case_sensitive) lit = self.literal.to(bound_term.ref().field.field_type) diff --git a/tests/expressions/test_expressions.py b/tests/expressions/test_expressions.py index 5a0c8c9241..02a584fb5c 100644 --- a/tests/expressions/test_expressions.py +++ b/tests/expressions/test_expressions.py @@ -55,8 +55,10 @@ NotIn, NotNaN, NotNull, + NotStartsWith, Or, Reference, + StartsWith, UnboundPredicate, ) from pyiceberg.expressions.literals import Literal, literal @@ -933,6 +935,7 @@ def test_bound_less_than_or_equal(term: BoundReference[Any]) -> None: def test_equal_to() -> None: equal_to = EqualTo(Reference("a"), literal("a")) + assert equal_to.model_dump_json() == '{"type":"eq","term":"a","value":"a"}' assert str(equal_to) == "EqualTo(term=Reference(name='a'), literal=literal('a'))" assert repr(equal_to) == "EqualTo(term=Reference(name='a'), literal=literal('a'))" assert equal_to == eval(repr(equal_to)) @@ -941,6 +944,7 @@ def test_equal_to() -> None: def test_not_equal_to() -> None: not_equal_to = NotEqualTo(Reference("a"), literal("a")) + assert not_equal_to.model_dump_json() == '{"type":"not-eq","term":"a","value":"a"}' assert str(not_equal_to) == "NotEqualTo(term=Reference(name='a'), literal=literal('a'))" assert repr(not_equal_to) == "NotEqualTo(term=Reference(name='a'), literal=literal('a'))" assert not_equal_to == eval(repr(not_equal_to)) @@ -949,6 +953,7 @@ def test_not_equal_to() -> None: def test_greater_than_or_equal_to() -> None: greater_than_or_equal_to = GreaterThanOrEqual(Reference("a"), literal("a")) + assert greater_than_or_equal_to.model_dump_json() == '{"type":"gt-eq","term":"a","value":"a"}' assert str(greater_than_or_equal_to) == "GreaterThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert repr(greater_than_or_equal_to) == "GreaterThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert greater_than_or_equal_to == eval(repr(greater_than_or_equal_to)) @@ -957,6 +962,7 @@ def test_greater_than_or_equal_to() -> None: def test_greater_than() -> None: greater_than = GreaterThan(Reference("a"), literal("a")) + assert greater_than.model_dump_json() == '{"type":"gt","term":"a","value":"a"}' assert str(greater_than) == "GreaterThan(term=Reference(name='a'), literal=literal('a'))" assert repr(greater_than) == "GreaterThan(term=Reference(name='a'), literal=literal('a'))" assert greater_than == eval(repr(greater_than)) @@ -965,14 +971,26 @@ def test_greater_than() -> None: def test_less_than() -> None: less_than = LessThan(Reference("a"), literal("a")) + assert less_than.model_dump_json() == '{"type":"lt","term":"a","value":"a"}' assert str(less_than) == "LessThan(term=Reference(name='a'), literal=literal('a'))" assert repr(less_than) == "LessThan(term=Reference(name='a'), literal=literal('a'))" assert less_than == eval(repr(less_than)) assert less_than == pickle.loads(pickle.dumps(less_than)) +def test_starts_with() -> None: + starts_with = StartsWith(Reference("a"), literal("a")) + assert starts_with.model_dump_json() == '{"type":"starts-with","term":"a","value":"a"}' + + +def test_not_starts_with() -> None: + not_starts_with = NotStartsWith(Reference("a"), literal("a")) + assert not_starts_with.model_dump_json() == '{"type":"not-starts-with","term":"a","value":"a"}' + + def test_less_than_or_equal() -> None: less_than_or_equal = LessThanOrEqual(Reference("a"), literal("a")) + assert less_than_or_equal.model_dump_json() == '{"type":"lt-eq","term":"a","value":"a"}' assert str(less_than_or_equal) == "LessThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert repr(less_than_or_equal) == "LessThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert less_than_or_equal == eval(repr(less_than_or_equal)) From c1f7384fe09ba11a1dc016c5d5febe5c9288065f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Fern=C3=A1ndez?= Date: Fri, 3 Oct 2025 18:55:15 +0200 Subject: [PATCH 2/5] feat: subclass LiteralPredicate instead of using internal class --- pyiceberg/expressions/__init__.py | 90 ++++++++++++++++----------- tests/expressions/test_expressions.py | 32 +++++----- 2 files changed, 68 insertions(+), 54 deletions(-) diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index 6834d2d80d..02c102df4c 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -17,11 +17,13 @@ from __future__ import annotations +import typing from abc import ABC, abstractmethod from functools import cached_property from typing import ( Any, Callable, + ClassVar, Generic, Iterable, Sequence, @@ -35,7 +37,7 @@ from pydantic import Field -from pydantic import Field +from pydantic import ConfigDict, Field, field_serializer, field_validator from pyiceberg.expressions.literals import ( AboveMax, @@ -745,45 +747,37 @@ def as_bound(self) -> Type[BoundNotIn[L]]: return BoundNotIn[L] -class LiteralPredicate(UnboundPredicate[L], ABC): - literal: Literal[L] +class LiteralPredicate(IcebergBaseModel, UnboundPredicate[L], ABC): + op: str = Field( + default="", + alias="type", + validation_alias="type", + serialization_alias="type", + repr=False, + ) + term: Term[L] + literal: Literal[L] = Field(serialization_alias="value") + + __op__: ClassVar[str] = "" + + model_config = ConfigDict(arbitrary_types_allowed=True) def __init__(self, term: Union[str, UnboundTerm[Any]], literal: Union[L, Literal[L]]): # pylint: disable=W0621 - super().__init__(term) - self.literal = _to_literal(literal) # pylint: disable=W0621 - - # ---- JSON (Pydantic) serialization helpers ---- - - class _LiteralPredicateModel(IcebergBaseModel): - type: str = Field(alias="type") - term: str - value: Any - - def _json_op(self) -> str: - mapping = { - EqualTo: "eq", - NotEqualTo: "not-eq", - LessThan: "lt", - LessThanOrEqual: "lt-eq", - GreaterThan: "gt", - GreaterThanOrEqual: "gt-eq", - StartsWith: "starts-with", - NotStartsWith: "not-starts-with", - } - for cls, op in mapping.items(): - if isinstance(self, cls): - return op - raise ValueError(f"Unknown LiteralPredicate: {type(self).__name__}") - - def model_dump(self, **kwargs: Any) -> dict: - term_name = getattr(self.term, "name", str(self.term)) - return self._LiteralPredicateModel(type=self._json_op(), term=term_name, value=self.literal.value).model_dump(**kwargs) - - def model_dump_json(self, **kwargs: Any) -> str: - term_name = getattr(self.term, "name", str(self.term)) - return self._LiteralPredicateModel(type=self._json_op(), term=term_name, value=self.literal.value).model_dump_json( - **kwargs - ) + super().__init__(term=_to_unbound_term(term), literal=_to_literal(literal)) + + def model_post_init(self, __context: Any) -> None: + if not self.op: + object.__setattr__(self, "op", self.__op__) + elif self.op != self.__op__: + raise ValueError(f"Invalid type {self.op!r}; expected {self.__op__!r}") + + @field_serializer("term") + def ser_term(self, v: Term[L]) -> str: + return v.name + + @field_serializer("literal") + def ser_literal(self, literal: Literal[L]) -> str: + return "Any" def bind(self, schema: Schema, case_sensitive: bool = True) -> BoundLiteralPredicate[L]: bound_term = self.term.bind(schema, case_sensitive) @@ -808,6 +802,10 @@ def __eq__(self, other: Any) -> bool: return self.term == other.term and self.literal == other.literal return False + def __str__(self) -> str: + """Return the string representation of the LiteralPredicate class.""" + return f"{str(self.__class__.__name__)}(term={repr(self.term)}, literal={repr(self.literal)})" + def __repr__(self) -> str: """Return the string representation of the LiteralPredicate class.""" return f"{str(self.__class__.__name__)}(term={repr(self.term)}, literal={repr(self.literal)})" @@ -921,6 +919,8 @@ def as_unbound(self) -> Type[NotStartsWith[L]]: class EqualTo(LiteralPredicate[L]): + __op__ = "eq" + def __invert__(self) -> NotEqualTo[L]: """Transform the Expression into its negated version.""" return NotEqualTo[L](self.term, self.literal) @@ -931,6 +931,8 @@ def as_bound(self) -> Type[BoundEqualTo[L]]: class NotEqualTo(LiteralPredicate[L]): + __op__ = "not-eq" + def __invert__(self) -> EqualTo[L]: """Transform the Expression into its negated version.""" return EqualTo[L](self.term, self.literal) @@ -941,6 +943,8 @@ def as_bound(self) -> Type[BoundNotEqualTo[L]]: class LessThan(LiteralPredicate[L]): + __op__ = "lt" + def __invert__(self) -> GreaterThanOrEqual[L]: """Transform the Expression into its negated version.""" return GreaterThanOrEqual[L](self.term, self.literal) @@ -951,6 +955,8 @@ def as_bound(self) -> Type[BoundLessThan[L]]: class GreaterThanOrEqual(LiteralPredicate[L]): + __op__ = "gt-eq" + def __invert__(self) -> LessThan[L]: """Transform the Expression into its negated version.""" return LessThan[L](self.term, self.literal) @@ -961,6 +967,8 @@ def as_bound(self) -> Type[BoundGreaterThanOrEqual[L]]: class GreaterThan(LiteralPredicate[L]): + __op__ = "gt" + def __invert__(self) -> LessThanOrEqual[L]: """Transform the Expression into its negated version.""" return LessThanOrEqual[L](self.term, self.literal) @@ -971,6 +979,8 @@ def as_bound(self) -> Type[BoundGreaterThan[L]]: class LessThanOrEqual(LiteralPredicate[L]): + __op__ = "lt-eq" + def __invert__(self) -> GreaterThan[L]: """Transform the Expression into its negated version.""" return GreaterThan[L](self.term, self.literal) @@ -981,6 +991,8 @@ def as_bound(self) -> Type[BoundLessThanOrEqual[L]]: class StartsWith(LiteralPredicate[L]): + __op__ = "starts-with" + def __invert__(self) -> NotStartsWith[L]: """Transform the Expression into its negated version.""" return NotStartsWith[L](self.term, self.literal) @@ -991,6 +1003,8 @@ def as_bound(self) -> Type[BoundStartsWith[L]]: class NotStartsWith(LiteralPredicate[L]): + __op__ = "not-starts-with" + def __invert__(self) -> StartsWith[L]: """Transform the Expression into its negated version.""" return StartsWith[L](self.term, self.literal) diff --git a/tests/expressions/test_expressions.py b/tests/expressions/test_expressions.py index 02a584fb5c..5d8035aea5 100644 --- a/tests/expressions/test_expressions.py +++ b/tests/expressions/test_expressions.py @@ -935,7 +935,7 @@ def test_bound_less_than_or_equal(term: BoundReference[Any]) -> None: def test_equal_to() -> None: equal_to = EqualTo(Reference("a"), literal("a")) - assert equal_to.model_dump_json() == '{"type":"eq","term":"a","value":"a"}' + assert equal_to.model_dump_json() == '{"term":"a","type":"eq","value":"Any"}' assert str(equal_to) == "EqualTo(term=Reference(name='a'), literal=literal('a'))" assert repr(equal_to) == "EqualTo(term=Reference(name='a'), literal=literal('a'))" assert equal_to == eval(repr(equal_to)) @@ -944,7 +944,7 @@ def test_equal_to() -> None: def test_not_equal_to() -> None: not_equal_to = NotEqualTo(Reference("a"), literal("a")) - assert not_equal_to.model_dump_json() == '{"type":"not-eq","term":"a","value":"a"}' + assert not_equal_to.model_dump_json() == '{"term":"a","type":"not-eq","value":"Any"}' assert str(not_equal_to) == "NotEqualTo(term=Reference(name='a'), literal=literal('a'))" assert repr(not_equal_to) == "NotEqualTo(term=Reference(name='a'), literal=literal('a'))" assert not_equal_to == eval(repr(not_equal_to)) @@ -953,7 +953,7 @@ def test_not_equal_to() -> None: def test_greater_than_or_equal_to() -> None: greater_than_or_equal_to = GreaterThanOrEqual(Reference("a"), literal("a")) - assert greater_than_or_equal_to.model_dump_json() == '{"type":"gt-eq","term":"a","value":"a"}' + assert greater_than_or_equal_to.model_dump_json() == '{"term":"a","type":"gt-eq","value":"Any"}' assert str(greater_than_or_equal_to) == "GreaterThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert repr(greater_than_or_equal_to) == "GreaterThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert greater_than_or_equal_to == eval(repr(greater_than_or_equal_to)) @@ -962,7 +962,7 @@ def test_greater_than_or_equal_to() -> None: def test_greater_than() -> None: greater_than = GreaterThan(Reference("a"), literal("a")) - assert greater_than.model_dump_json() == '{"type":"gt","term":"a","value":"a"}' + assert greater_than.model_dump_json() == '{"term":"a","type":"gt","value":"Any"}' assert str(greater_than) == "GreaterThan(term=Reference(name='a'), literal=literal('a'))" assert repr(greater_than) == "GreaterThan(term=Reference(name='a'), literal=literal('a'))" assert greater_than == eval(repr(greater_than)) @@ -971,32 +971,32 @@ def test_greater_than() -> None: def test_less_than() -> None: less_than = LessThan(Reference("a"), literal("a")) - assert less_than.model_dump_json() == '{"type":"lt","term":"a","value":"a"}' + assert less_than.model_dump_json() == '{"term":"a","type":"lt","value":"Any"}' assert str(less_than) == "LessThan(term=Reference(name='a'), literal=literal('a'))" assert repr(less_than) == "LessThan(term=Reference(name='a'), literal=literal('a'))" assert less_than == eval(repr(less_than)) assert less_than == pickle.loads(pickle.dumps(less_than)) -def test_starts_with() -> None: - starts_with = StartsWith(Reference("a"), literal("a")) - assert starts_with.model_dump_json() == '{"type":"starts-with","term":"a","value":"a"}' - - -def test_not_starts_with() -> None: - not_starts_with = NotStartsWith(Reference("a"), literal("a")) - assert not_starts_with.model_dump_json() == '{"type":"not-starts-with","term":"a","value":"a"}' - - def test_less_than_or_equal() -> None: less_than_or_equal = LessThanOrEqual(Reference("a"), literal("a")) - assert less_than_or_equal.model_dump_json() == '{"type":"lt-eq","term":"a","value":"a"}' + assert less_than_or_equal.model_dump_json() == '{"term":"a","type":"lt-eq","value":"Any"}' assert str(less_than_or_equal) == "LessThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert repr(less_than_or_equal) == "LessThanOrEqual(term=Reference(name='a'), literal=literal('a'))" assert less_than_or_equal == eval(repr(less_than_or_equal)) assert less_than_or_equal == pickle.loads(pickle.dumps(less_than_or_equal)) +def test_starts_with() -> None: + starts_with = StartsWith(Reference("a"), literal("a")) + assert starts_with.model_dump_json() == '{"term":"a","type":"starts-with","value":"Any"}' + + +def test_not_starts_with() -> None: + not_starts_with = NotStartsWith(Reference("a"), literal("a")) + assert not_starts_with.model_dump_json() == '{"term":"a","type":"not-starts-with","value":"Any"}' + + def test_bound_reference_eval(table_schema_simple: Schema) -> None: """Test creating a BoundReference and evaluating it on a StructProtocol""" struct = Record("foovalue", 123, True) From 482f4e02877cbedf5a21073e7c24ae4cf48b3bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Fern=C3=A1ndez?= Date: Fri, 10 Oct 2025 19:43:30 +0200 Subject: [PATCH 3/5] fix: use type in main class only and remove __op__ --- pyiceberg/expressions/__init__.py | 38 ++++++++----------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index 02c102df4c..923e462b45 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -17,13 +17,11 @@ from __future__ import annotations -import typing from abc import ABC, abstractmethod from functools import cached_property from typing import ( Any, Callable, - ClassVar, Generic, Iterable, Sequence, @@ -35,9 +33,7 @@ ) from typing import Literal as TypingLiteral -from pydantic import Field - -from pydantic import ConfigDict, Field, field_serializer, field_validator +from pydantic import ConfigDict, Field, field_serializer from pyiceberg.expressions.literals import ( AboveMax, @@ -748,29 +744,15 @@ def as_bound(self) -> Type[BoundNotIn[L]]: class LiteralPredicate(IcebergBaseModel, UnboundPredicate[L], ABC): - op: str = Field( - default="", - alias="type", - validation_alias="type", - serialization_alias="type", - repr=False, - ) + type: TypingLiteral["lt-eq", "gt", "gt-eq", "eq", "not-eq", "starts-with", "not-starts-with"] = Field(alias="type") term: Term[L] literal: Literal[L] = Field(serialization_alias="value") - __op__: ClassVar[str] = "" - model_config = ConfigDict(arbitrary_types_allowed=True) def __init__(self, term: Union[str, UnboundTerm[Any]], literal: Union[L, Literal[L]]): # pylint: disable=W0621 super().__init__(term=_to_unbound_term(term), literal=_to_literal(literal)) - def model_post_init(self, __context: Any) -> None: - if not self.op: - object.__setattr__(self, "op", self.__op__) - elif self.op != self.__op__: - raise ValueError(f"Invalid type {self.op!r}; expected {self.__op__!r}") - @field_serializer("term") def ser_term(self, v: Term[L]) -> str: return v.name @@ -919,7 +901,7 @@ def as_unbound(self) -> Type[NotStartsWith[L]]: class EqualTo(LiteralPredicate[L]): - __op__ = "eq" + type: TypingLiteral["eq"] = Field(default="eq", alias="type") def __invert__(self) -> NotEqualTo[L]: """Transform the Expression into its negated version.""" @@ -931,7 +913,7 @@ def as_bound(self) -> Type[BoundEqualTo[L]]: class NotEqualTo(LiteralPredicate[L]): - __op__ = "not-eq" + type: TypingLiteral["not-eq"] = Field(default="not-eq", alias="type") def __invert__(self) -> EqualTo[L]: """Transform the Expression into its negated version.""" @@ -943,7 +925,7 @@ def as_bound(self) -> Type[BoundNotEqualTo[L]]: class LessThan(LiteralPredicate[L]): - __op__ = "lt" + type: TypingLiteral["lt"] = Field(default="lt", alias="type") def __invert__(self) -> GreaterThanOrEqual[L]: """Transform the Expression into its negated version.""" @@ -955,7 +937,7 @@ def as_bound(self) -> Type[BoundLessThan[L]]: class GreaterThanOrEqual(LiteralPredicate[L]): - __op__ = "gt-eq" + type: TypingLiteral["gt-eq"] = Field(default="gt-eq", alias="type") def __invert__(self) -> LessThan[L]: """Transform the Expression into its negated version.""" @@ -967,7 +949,7 @@ def as_bound(self) -> Type[BoundGreaterThanOrEqual[L]]: class GreaterThan(LiteralPredicate[L]): - __op__ = "gt" + type: TypingLiteral["gt"] = Field(default="gt", alias="type") def __invert__(self) -> LessThanOrEqual[L]: """Transform the Expression into its negated version.""" @@ -979,7 +961,7 @@ def as_bound(self) -> Type[BoundGreaterThan[L]]: class LessThanOrEqual(LiteralPredicate[L]): - __op__ = "lt-eq" + type: TypingLiteral["lt-eq"] = Field(default="lt-eq", alias="type") def __invert__(self) -> GreaterThan[L]: """Transform the Expression into its negated version.""" @@ -991,7 +973,7 @@ def as_bound(self) -> Type[BoundLessThanOrEqual[L]]: class StartsWith(LiteralPredicate[L]): - __op__ = "starts-with" + type: TypingLiteral["starts-with"] = Field(default="starts-with", alias="type") def __invert__(self) -> NotStartsWith[L]: """Transform the Expression into its negated version.""" @@ -1003,7 +985,7 @@ def as_bound(self) -> Type[BoundStartsWith[L]]: class NotStartsWith(LiteralPredicate[L]): - __op__ = "not-starts-with" + type: TypingLiteral["not-starts-with"] = Field(default="not-starts-with", alias="type") def __invert__(self) -> StartsWith[L]: """Transform the Expression into its negated version.""" From dd7e09bb7732d7696b4fb053077fd2d481b0e979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Fern=C3=A1ndez?= Date: Sat, 11 Oct 2025 00:32:54 +0200 Subject: [PATCH 4/5] fix adding lt literal and allow boundreference in _to_unbound_term --- pyiceberg/expressions/__init__.py | 38 ++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index 923e462b45..883a042d54 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -33,7 +33,7 @@ ) from typing import Literal as TypingLiteral -from pydantic import ConfigDict, Field, field_serializer +from pydantic import ConfigDict, Field, field_serializer, field_validator from pyiceberg.expressions.literals import ( AboveMax, @@ -52,8 +52,14 @@ ConfigDict = dict -def _to_unbound_term(term: Union[str, UnboundTerm[Any]]) -> UnboundTerm[Any]: - return Reference(term) if isinstance(term, str) else term +def _to_unbound_term(term: Union[str, UnboundTerm[Any], BoundReference[Any]]) -> UnboundTerm[Any]: + if isinstance(term, str): + return Reference(term) + if isinstance(term, UnboundTerm): + return term + if isinstance(term, BoundReference): + return Reference(term.field.name) + raise ValueError(f"Expected UnboundTerm | BoundReference | str, got {type(term).__name__}") def _to_literal_set(values: Union[Iterable[L], Iterable[Literal[L]]]) -> Set[Literal[L]]: @@ -744,18 +750,28 @@ def as_bound(self) -> Type[BoundNotIn[L]]: class LiteralPredicate(IcebergBaseModel, UnboundPredicate[L], ABC): - type: TypingLiteral["lt-eq", "gt", "gt-eq", "eq", "not-eq", "starts-with", "not-starts-with"] = Field(alias="type") - term: Term[L] + type: TypingLiteral["lt", "lt-eq", "gt", "gt-eq", "eq", "not-eq", "starts-with", "not-starts-with"] = Field(alias="type") + term: UnboundTerm[L] literal: Literal[L] = Field(serialization_alias="value") model_config = ConfigDict(arbitrary_types_allowed=True) - def __init__(self, term: Union[str, UnboundTerm[Any]], literal: Union[L, Literal[L]]): # pylint: disable=W0621 - super().__init__(term=_to_unbound_term(term), literal=_to_literal(literal)) - - @field_serializer("term") - def ser_term(self, v: Term[L]) -> str: - return v.name + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args: + if len(args) != 2: + raise TypeError("Expected (term, literal)") + kwargs = {"term": args[0], "literal": args[1], **kwargs} + super().__init__(**kwargs) + + @field_validator("term", mode="before") + @classmethod + def _coerce_term(cls, v: Any) -> UnboundTerm[Any]: + return _to_unbound_term(v) + + @field_validator("literal", mode="before") + @classmethod + def _coerce_literal(cls, v: Union[L, Literal[L]]) -> Literal[L]: + return _to_literal(v) @field_serializer("literal") def ser_literal(self, literal: Literal[L]) -> str: From 51187480284c6a3fcb70070c972e86839c3896c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Fern=C3=A1ndez?= Date: Sat, 11 Oct 2025 00:35:46 +0200 Subject: [PATCH 5/5] fix: remove type hinting errors --- tests/expressions/test_evaluator.py | 4 ++-- tests/expressions/test_expressions.py | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/expressions/test_evaluator.py b/tests/expressions/test_evaluator.py index cfc32d9b6b..7b15099105 100644 --- a/tests/expressions/test_evaluator.py +++ b/tests/expressions/test_evaluator.py @@ -683,7 +683,7 @@ def data_file_nan() -> DataFile: def test_inclusive_metrics_evaluator_less_than_and_less_than_equal(schema_data_file_nan: Schema, data_file_nan: DataFile) -> None: - for operator in [LessThan, LessThanOrEqual]: # type: ignore + for operator in [LessThan, LessThanOrEqual]: should_read = _InclusiveMetricsEvaluator(schema_data_file_nan, operator("all_nan", 1)).eval(data_file_nan) # type: ignore[arg-type] assert not should_read, "Should not match: all nan column doesn't contain number" @@ -711,7 +711,7 @@ def test_inclusive_metrics_evaluator_less_than_and_less_than_equal(schema_data_f def test_inclusive_metrics_evaluator_greater_than_and_greater_than_equal( schema_data_file_nan: Schema, data_file_nan: DataFile ) -> None: - for operator in [GreaterThan, GreaterThanOrEqual]: # type: ignore + for operator in [GreaterThan, GreaterThanOrEqual]: should_read = _InclusiveMetricsEvaluator(schema_data_file_nan, operator("all_nan", 1)).eval(data_file_nan) # type: ignore[arg-type] assert not should_read, "Should not match: all nan column doesn't contain number" diff --git a/tests/expressions/test_expressions.py b/tests/expressions/test_expressions.py index 5d8035aea5..16ceb5ad2a 100644 --- a/tests/expressions/test_expressions.py +++ b/tests/expressions/test_expressions.py @@ -429,14 +429,14 @@ def test_bound_less_than_or_equal_invert(table_schema_simple: Schema) -> None: def test_not_equal_to_invert() -> None: bound = NotEqualTo( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ), literal="hello", ) assert ~bound == EqualTo( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ), @@ -446,14 +446,14 @@ def test_not_equal_to_invert() -> None: def test_greater_than_or_equal_invert() -> None: bound = GreaterThanOrEqual( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ), literal="hello", ) assert ~bound == LessThan( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ), @@ -463,14 +463,14 @@ def test_greater_than_or_equal_invert() -> None: def test_less_than_or_equal_invert() -> None: bound = LessThanOrEqual( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ), literal="hello", ) assert ~bound == GreaterThan( - term=BoundReference( # type: ignore + term=BoundReference( field=NestedField(field_id=1, name="foo", field_type=StringType(), required=False), accessor=Accessor(position=0, inner=None), ),