-
Notifications
You must be signed in to change notification settings - Fork 3
Update PolarsExpression to just be a type annotation on pl.Expr #130
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ae87506
Add PolarsExpr type annotation for pydantic validation without subcla…
NeejWeej 95c02a3
Import annotated from typing
NeejWeej b19dfb3
Remove PolarsExpr
NeejWeej c312df2
Merge branch 'main' into nk/polars_expr_annotated
NeejWeej 7e84053
Merge branch 'main' into nk/polars_expr_annotated
NeejWeej c8aaf03
Merge branch 'main' into nk/polars_expr_annotated
NeejWeej File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,56 +1,99 @@ | ||
| import math | ||
| from unittest import TestCase | ||
|
|
||
| import numpy as np | ||
| import polars as pl | ||
| import pytest | ||
| import scipy | ||
| from packaging import version | ||
| from pydantic import TypeAdapter | ||
| from pydantic import TypeAdapter, ValidationError | ||
|
|
||
| from ccflow.exttypes.polars import PolarsExpression | ||
| from ccflow import BaseModel | ||
| from ccflow.exttypes.polars import PolarsExpr, PolarsExpression | ||
|
|
||
|
|
||
| class TestPolarsExpression(TestCase): | ||
| def test_expression(self): | ||
| expression = pl.col("Col1") + pl.col("Col2") | ||
| self.assertEqual(PolarsExpression.validate(expression).meta.serialize(), expression.meta.serialize()) | ||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_expression_passthrough(typ): | ||
| adapter = TypeAdapter(typ) | ||
| expression = pl.col("Col1") + pl.col("Col2") | ||
| result = adapter.validate_python(expression) | ||
| assert result.meta.serialize() == expression.meta.serialize() | ||
|
|
||
| def test_expression_deserialization(self): | ||
| expression = PolarsExpression.validate("pl.col('Col1') + pl.col('Col2')") | ||
| expected_result = pl.col("Col1") + pl.col("Col2") | ||
|
|
||
| self.assertEqual(expression.meta.serialize(), expected_result.meta.serialize()) | ||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_expression_from_string(typ): | ||
| adapter = TypeAdapter(typ) | ||
| expected_result = pl.col("Col1") + pl.col("Col2") | ||
| expression = adapter.validate_python("pl.col('Col1') + pl.col('Col2')") | ||
| assert expression.meta.serialize() == expected_result.meta.serialize() | ||
|
|
||
| def test_expression_complex(self): | ||
| expression = PolarsExpression.validate( | ||
| "col('Col1') + (sp.linalg.det(numpy.eye(2, dtype=int)) - 1 ) * math.pi * c('Col2') + polars.col('Col2')" | ||
| ) | ||
| expected_result = pl.col("Col1") + (scipy.linalg.det(np.eye(2, dtype=int)) - 1) * math.pi * pl.col("Col2") + pl.col("Col2") | ||
|
|
||
| self.assertEqual( | ||
| PolarsExpression.validate(expression).meta.serialize(), | ||
| expected_result.meta.serialize(), | ||
| ) | ||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_expression_complex(typ): | ||
| adapter = TypeAdapter(typ) | ||
| expected_result = pl.col("Col1") + (scipy.linalg.det(np.eye(2, dtype=int)) - 1) * math.pi * pl.col("Col2") + pl.col("Col2") | ||
| expression = adapter.validate_python("col('Col1') + (sp.linalg.det(numpy.eye(2, dtype=int)) - 1 ) * math.pi * c('Col2') + polars.col('Col2')") | ||
| assert expression.meta.serialize() == expected_result.meta.serialize() | ||
|
|
||
| def test_validation_failure(self): | ||
| with self.assertRaises(ValueError): | ||
| PolarsExpression.validate(None) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| PolarsExpression.validate("pl.DataFrame()") | ||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_validation_failure(typ): | ||
| adapter = TypeAdapter(typ) | ||
| with pytest.raises(ValidationError): | ||
| adapter.validate_python(None) | ||
| with pytest.raises(ValidationError): | ||
| adapter.validate_python("pl.DataFrame()") | ||
|
|
||
| def test_validation_eval_failure(self): | ||
| with self.assertRaises(ValueError): | ||
| PolarsExpression.validate("invalid_statement") | ||
|
|
||
| def test_json_serialization(self): | ||
| expression = pl.col("Col1") + pl.col("Col2") | ||
| json_result = TypeAdapter(PolarsExpression).dump_json(expression) | ||
| if version.parse(pl.__version__) < version.parse("1.0.0"): | ||
| self.assertEqual(json_result.decode("utf-8"), expression.meta.serialize()) | ||
| else: | ||
| # polars serializes into a binary format by default. | ||
| self.assertEqual(json_result.decode("utf-8"), expression.meta.serialize(format="json")) | ||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_validation_eval_failure(typ): | ||
| adapter = TypeAdapter(typ) | ||
| with pytest.raises(ValidationError): | ||
| adapter.validate_python("invalid_statement") | ||
|
|
||
| expected_result = TypeAdapter(PolarsExpression).validate_json(json_result) | ||
| self.assertEqual(expected_result.meta.serialize(), expression.meta.serialize()) | ||
|
|
||
| @pytest.mark.parametrize("typ", [PolarsExpression, PolarsExpr]) | ||
| def test_json_serialization_roundtrip(typ): | ||
| adapter = TypeAdapter(typ) | ||
| expression = pl.col("Col1") + pl.col("Col2") | ||
| json_result = adapter.dump_json(expression) | ||
| if version.parse(pl.__version__) < version.parse("1.0.0"): | ||
| assert json_result.decode("utf-8") == expression.meta.serialize() | ||
| else: | ||
| assert json_result.decode("utf-8") == expression.meta.serialize(format="json") | ||
|
|
||
| expected_result = adapter.validate_json(json_result) | ||
| assert expected_result.meta.serialize() == expression.meta.serialize() | ||
|
|
||
|
|
||
| def test_model_field_and_dataframe_filter(): | ||
| class DummyExprModel(BaseModel): | ||
| expr: PolarsExpr | ||
|
|
||
| m = DummyExprModel(expr="pl.col('x') > 10") | ||
| assert isinstance(m.expr, pl.Expr) | ||
|
|
||
| df = pl.DataFrame({"x": [5, 10, 11, 20], "y": [1, 2, 3, 4]}) | ||
| filtered = df.filter(m.expr) | ||
| assert filtered.select("x").to_series().to_list() == [11, 20] | ||
|
|
||
|
|
||
| # Explicitly test the legacy classmethod validator for backwards compatibility | ||
| def test_polars_expression_validate_passthrough(): | ||
| expression = pl.col("Col1") + pl.col("Col2") | ||
| result = PolarsExpression.validate(expression) | ||
| assert result.meta.serialize() == expression.meta.serialize() | ||
|
|
||
|
|
||
| def test_polars_expression_validate_from_string(): | ||
| result = PolarsExpression.validate("pl.col('Col1') + pl.col('Col2')") | ||
| expected_result = pl.col("Col1") + pl.col("Col2") | ||
| assert result.meta.serialize() == expected_result.meta.serialize() | ||
|
|
||
|
|
||
| def test_polars_expression_validate_errors(): | ||
| with pytest.raises(ValueError): | ||
| PolarsExpression.validate(None) | ||
| with pytest.raises(ValueError): | ||
| PolarsExpression.validate("pl.DataFrame()") | ||
| with pytest.raises(ValueError): | ||
| PolarsExpression.validate("invalid_statement") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.