pavise 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pavise/__init__.py +4 -0
- pavise/_pandas/__init__.py +1 -0
- pavise/_pandas/validation.py +292 -0
- pavise/_pandas/validator_impl.py +144 -0
- pavise/_polars/__init__.py +1 -0
- pavise/_polars/validation.py +178 -0
- pavise/_polars/validator_impl.py +150 -0
- pavise/exceptions.py +63 -0
- pavise/pandas.py +54 -0
- pavise/polars.py +57 -0
- pavise/validators.py +74 -0
- pavise-0.0.1.dist-info/METADATA +222 -0
- pavise-0.0.1.dist-info/RECORD +14 -0
- pavise-0.0.1.dist-info/WHEEL +4 -0
pavise/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Pandas-specific implementation details."""
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Common validation functions for DataFrame schema checking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import date, datetime, timedelta
|
|
7
|
+
from typing import Annotated, Callable, Union, get_args, get_origin, get_type_hints
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from pavise.exceptions import ValidationError
|
|
13
|
+
|
|
14
|
+
# Maximum number of invalid sample values to show in error messages
|
|
15
|
+
MAX_SAMPLE_SIZE = 5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class TypeChecker:
|
|
20
|
+
"""Type checker with both dtype-level and value-level validation."""
|
|
21
|
+
|
|
22
|
+
dtype: Callable[[pd.Series | pd.Index], bool] # Check dtype of entire Series
|
|
23
|
+
value: Callable[[object], bool] # Check individual values
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def type_check_str(df: pd.Series | pd.Index) -> bool:
|
|
27
|
+
df = pd.Series(df)
|
|
28
|
+
if pd.api.types.is_string_dtype(df):
|
|
29
|
+
return True
|
|
30
|
+
elif df.dtype == object:
|
|
31
|
+
return bool(df.apply(lambda x: isinstance(x, str) or pd.isna(x)).all())
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
TYPE_CHECKERS = {
|
|
36
|
+
int: TypeChecker(
|
|
37
|
+
dtype=pd.api.types.is_integer_dtype,
|
|
38
|
+
value=lambda x: isinstance(x, (int, np.integer)) or pd.isna(x),
|
|
39
|
+
),
|
|
40
|
+
float: TypeChecker(
|
|
41
|
+
dtype=pd.api.types.is_float_dtype,
|
|
42
|
+
value=lambda x: isinstance(x, (float, np.floating)) or pd.isna(x),
|
|
43
|
+
),
|
|
44
|
+
str: TypeChecker(
|
|
45
|
+
dtype=type_check_str,
|
|
46
|
+
value=lambda x: isinstance(x, str) or pd.isna(x),
|
|
47
|
+
),
|
|
48
|
+
bool: TypeChecker(
|
|
49
|
+
dtype=pd.api.types.is_bool_dtype,
|
|
50
|
+
value=lambda x: isinstance(x, (bool, np.bool_)) or pd.isna(x),
|
|
51
|
+
),
|
|
52
|
+
datetime: TypeChecker(
|
|
53
|
+
dtype=pd.api.types.is_datetime64_any_dtype,
|
|
54
|
+
value=lambda x: isinstance(x, (pd.Timestamp, datetime)) or pd.isna(x),
|
|
55
|
+
),
|
|
56
|
+
date: TypeChecker(
|
|
57
|
+
dtype=pd.api.types.is_datetime64_any_dtype,
|
|
58
|
+
value=lambda x: isinstance(x, (pd.Timestamp, datetime, date)) or pd.isna(x),
|
|
59
|
+
),
|
|
60
|
+
timedelta: TypeChecker(
|
|
61
|
+
dtype=pd.api.types.is_timedelta64_dtype,
|
|
62
|
+
value=lambda x: isinstance(x, (pd.Timedelta, timedelta)) or pd.isna(x),
|
|
63
|
+
),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate_dataframe(df: pd.DataFrame, schema: type) -> None:
|
|
68
|
+
"""
|
|
69
|
+
Validate that a DataFrame conforms to a Protocol schema.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
df: DataFrame to validate
|
|
73
|
+
schema: Protocol type defining the expected schema
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
ValueError: If a required column is missing or type is unsupported
|
|
77
|
+
TypeError: If a column has the wrong type
|
|
78
|
+
"""
|
|
79
|
+
expected_cols = get_type_hints(schema, include_extras=True)
|
|
80
|
+
|
|
81
|
+
for col_name, col_type in expected_cols.items():
|
|
82
|
+
if col_name == "__index__":
|
|
83
|
+
_check_index_type(df, col_type)
|
|
84
|
+
else:
|
|
85
|
+
_check_column_exists(df, col_name)
|
|
86
|
+
_check_column_type(df, col_name, col_type)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _extract_type_and_validators(annotation: type) -> tuple[type, list, bool]:
|
|
90
|
+
"""
|
|
91
|
+
Extract base type, validators, and nullable flag from a type annotation.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
annotation: Type annotation (e.g., int, Optional[int], or Annotated[int, Range(0, 100)])
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Tuple of (base_type, validators, is_optional)
|
|
98
|
+
- For Annotated[int, Range(0, 100)]: (int, [Range(0, 100)], False)
|
|
99
|
+
- For int: (int, [], False)
|
|
100
|
+
- For Optional[int]: (int, [], True)
|
|
101
|
+
- For Annotated[Optional[int], Range(0, 100)]: (int, [Range(0, 100)], True)
|
|
102
|
+
"""
|
|
103
|
+
validators = []
|
|
104
|
+
is_optional = False
|
|
105
|
+
|
|
106
|
+
if get_origin(annotation) is Annotated:
|
|
107
|
+
args = get_args(annotation)
|
|
108
|
+
base_type = args[0]
|
|
109
|
+
validators = list(args[1:])
|
|
110
|
+
annotation = base_type
|
|
111
|
+
|
|
112
|
+
origin = get_origin(annotation)
|
|
113
|
+
if origin is Union:
|
|
114
|
+
args = get_args(annotation)
|
|
115
|
+
if len(args) == 2 and type(None) in args:
|
|
116
|
+
is_optional = True
|
|
117
|
+
base_type = args[0] if args[1] is type(None) else args[1]
|
|
118
|
+
return base_type, validators, is_optional
|
|
119
|
+
|
|
120
|
+
return annotation, validators, is_optional
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _extract_index_name_type_and_validators(
|
|
124
|
+
annotation: type,
|
|
125
|
+
) -> tuple[type, str | tuple[str, ...] | None, list, bool]:
|
|
126
|
+
"""
|
|
127
|
+
Extract base type, index name, validators, and nullable flag from an index type annotation.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
annotation: Type annotation for index (e.g., int, Annotated[int, "user_id"])
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
Tuple of (base_type, index_name, validators, is_optional)
|
|
134
|
+
- For Annotated[int, "user_id"]: (int, "user_id", [], False)
|
|
135
|
+
- For Annotated[int, "user_id", Range(0, 100)]: (int, "user_id", [Range(0, 100)], False)
|
|
136
|
+
- For Annotated[tuple[str, int], ("region", "user_id")]:
|
|
137
|
+
(tuple[str, int], ("region", "user_id"), [], False)
|
|
138
|
+
- For Annotated[int, Range(0, 100)]: (int, None, [Range(0, 100)], False)
|
|
139
|
+
- For int: (int, None, [], False)
|
|
140
|
+
"""
|
|
141
|
+
index_name = None
|
|
142
|
+
validators = []
|
|
143
|
+
is_optional = False
|
|
144
|
+
|
|
145
|
+
if get_origin(annotation) is Annotated:
|
|
146
|
+
args = get_args(annotation)
|
|
147
|
+
base_type = args[0]
|
|
148
|
+
metadata = list(args[1:])
|
|
149
|
+
|
|
150
|
+
if metadata and isinstance(metadata[0], (str, tuple)):
|
|
151
|
+
index_name = metadata[0]
|
|
152
|
+
validators = metadata[1:]
|
|
153
|
+
else:
|
|
154
|
+
validators = metadata
|
|
155
|
+
|
|
156
|
+
annotation = base_type
|
|
157
|
+
|
|
158
|
+
origin = get_origin(annotation)
|
|
159
|
+
if origin is Union:
|
|
160
|
+
args = get_args(annotation)
|
|
161
|
+
if len(args) == 2 and type(None) in args:
|
|
162
|
+
is_optional = True
|
|
163
|
+
base_type = args[0] if args[1] is type(None) else args[1]
|
|
164
|
+
return base_type, index_name, validators, is_optional
|
|
165
|
+
|
|
166
|
+
return annotation, index_name, validators, is_optional
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _check_index_type(df: pd.DataFrame, expected_type: type) -> None:
|
|
170
|
+
"""Check if index has the expected type and name."""
|
|
171
|
+
from pavise._pandas.validator_impl import apply_validator
|
|
172
|
+
|
|
173
|
+
base_type, index_name, validators, is_optional = _extract_index_name_type_and_validators(
|
|
174
|
+
expected_type
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
if get_origin(base_type) is tuple:
|
|
178
|
+
if not (index_name is None or isinstance(index_name, tuple)):
|
|
179
|
+
raise ValidationError("MultiIndex must have a tuple of names specified in Annotated")
|
|
180
|
+
_check_multiindex_type(df, base_type, index_name, validators, is_optional)
|
|
181
|
+
else:
|
|
182
|
+
if index_name is not None:
|
|
183
|
+
if df.index.name != index_name:
|
|
184
|
+
raise ValidationError(f"Index name expected '{index_name}', got {df.index.name!r}")
|
|
185
|
+
|
|
186
|
+
if base_type not in TYPE_CHECKERS:
|
|
187
|
+
raise ValidationError(f"unsupported type: {base_type}")
|
|
188
|
+
|
|
189
|
+
checker = TYPE_CHECKERS[base_type]
|
|
190
|
+
if not checker.dtype(df.index):
|
|
191
|
+
raise ValidationError(f"Index expected {base_type.__name__}, got {df.index.dtype}")
|
|
192
|
+
|
|
193
|
+
index_series = pd.Series(df.index)
|
|
194
|
+
for validator in validators:
|
|
195
|
+
apply_validator(index_series, validator, "Index")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _check_multiindex_type(
|
|
199
|
+
df: pd.DataFrame,
|
|
200
|
+
expected_types: type,
|
|
201
|
+
index_names: tuple[str, ...] | None,
|
|
202
|
+
validators: list,
|
|
203
|
+
is_optional: bool,
|
|
204
|
+
) -> None:
|
|
205
|
+
"""Check if MultiIndex has the expected types and names."""
|
|
206
|
+
from pavise._pandas.validator_impl import apply_validator
|
|
207
|
+
|
|
208
|
+
level_types = get_args(expected_types)
|
|
209
|
+
|
|
210
|
+
if not isinstance(df.index, pd.MultiIndex):
|
|
211
|
+
raise ValidationError(
|
|
212
|
+
f"Expected MultiIndex with {len(level_types)} levels, got {type(df.index).__name__}"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
if len(df.index.levels) != len(level_types):
|
|
216
|
+
raise ValidationError(
|
|
217
|
+
f"Expected MultiIndex with {len(level_types)} levels, got {len(df.index.levels)}"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
if index_names is not None:
|
|
221
|
+
if tuple(df.index.names) != index_names:
|
|
222
|
+
raise ValidationError(
|
|
223
|
+
f"Index names expected {index_names!r}, got {tuple(df.index.names)!r}"
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
for level_idx, level_type in enumerate(level_types):
|
|
227
|
+
if level_type not in TYPE_CHECKERS:
|
|
228
|
+
raise ValidationError(f"Unsupported type: {level_type}")
|
|
229
|
+
|
|
230
|
+
checker = TYPE_CHECKERS[level_type]
|
|
231
|
+
level_data = df.index.get_level_values(level_idx)
|
|
232
|
+
|
|
233
|
+
if not checker.dtype(level_data):
|
|
234
|
+
raise ValidationError(
|
|
235
|
+
f"Index level {level_idx} expected {level_type.__name__}, got {level_data.dtype}"
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
if validators:
|
|
239
|
+
for level_idx in range(len(level_types)):
|
|
240
|
+
level_series = pd.Series(df.index.get_level_values(level_idx))
|
|
241
|
+
for validator in validators:
|
|
242
|
+
apply_validator(level_series, validator, f"Index level {level_idx}")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _check_column_exists(df: pd.DataFrame, col_name: str) -> None:
|
|
246
|
+
"""Check if a column exists in the DataFrame."""
|
|
247
|
+
if col_name not in df.columns:
|
|
248
|
+
raise ValidationError("missing", column_name=col_name)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _check_column_type(df: pd.DataFrame, col_name: str, expected_type: type) -> None:
|
|
252
|
+
"""Check if a column has the expected type and apply validators."""
|
|
253
|
+
from pavise._pandas.validator_impl import apply_validator
|
|
254
|
+
|
|
255
|
+
base_type, validators, is_optional = _extract_type_and_validators(expected_type)
|
|
256
|
+
|
|
257
|
+
if isinstance(base_type, type) and issubclass(base_type, pd.api.extensions.ExtensionDtype):
|
|
258
|
+
col_dtype = df[col_name].dtype
|
|
259
|
+
if type(col_dtype) is not base_type:
|
|
260
|
+
base_tname = base_type.__name__
|
|
261
|
+
col_tname = type(col_dtype).__name__
|
|
262
|
+
raise ValidationError(
|
|
263
|
+
f"expected {base_tname}, got {col_tname}",
|
|
264
|
+
column_name=col_name,
|
|
265
|
+
)
|
|
266
|
+
for validator in validators:
|
|
267
|
+
apply_validator(df[col_name], validator, col_name)
|
|
268
|
+
return
|
|
269
|
+
|
|
270
|
+
if base_type not in TYPE_CHECKERS:
|
|
271
|
+
raise ValidationError(f"unsupported type: {base_type}", column_name=col_name)
|
|
272
|
+
|
|
273
|
+
checker = TYPE_CHECKERS[base_type]
|
|
274
|
+
col_dtype = df[col_name].dtype
|
|
275
|
+
|
|
276
|
+
if not is_optional and df[col_name].isna().any():
|
|
277
|
+
raise ValidationError("is non-optional but contains null values", column_name=col_name)
|
|
278
|
+
if not checker.dtype(df[col_name]):
|
|
279
|
+
invalid_mask = df[col_name].apply(checker.value)
|
|
280
|
+
invalid_df = df[col_name][~invalid_mask]
|
|
281
|
+
samples = [(idx, invalid_df[idx]) for idx in invalid_df.index]
|
|
282
|
+
samples = samples[:MAX_SAMPLE_SIZE]
|
|
283
|
+
raise ValidationError.new_with_samples(
|
|
284
|
+
col_name,
|
|
285
|
+
f"expected {base_type.__name__}, got {col_dtype}",
|
|
286
|
+
samples,
|
|
287
|
+
len(df[col_name][~invalid_mask]),
|
|
288
|
+
repr,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
for validator in validators:
|
|
292
|
+
apply_validator(df[col_name], validator, col_name)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Pandas-specific validator implementations."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from pavise.exceptions import ValidationError
|
|
8
|
+
from pavise.validators import In, MaxLen, MinLen, Range, Regex, Unique
|
|
9
|
+
|
|
10
|
+
# Maximum number of invalid sample values to show in error messages
|
|
11
|
+
MAX_SAMPLE_SIZE = 5
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def apply_validator(series: pd.Series, validator: Any, col_name: str) -> None:
|
|
15
|
+
"""
|
|
16
|
+
Apply a validator to a pandas Series.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
series: pandas Series to validate
|
|
20
|
+
validator: Validator instance (e.g., Range, Unique, In, Regex, MinLen, MaxLen)
|
|
21
|
+
col_name: column name for error messages
|
|
22
|
+
|
|
23
|
+
Raises:
|
|
24
|
+
ValueError: if validation fails
|
|
25
|
+
"""
|
|
26
|
+
if isinstance(validator, Range):
|
|
27
|
+
_validate_range(series, validator, col_name)
|
|
28
|
+
elif isinstance(validator, Unique):
|
|
29
|
+
_validate_unique(series, col_name)
|
|
30
|
+
elif isinstance(validator, In):
|
|
31
|
+
_validate_in(series, validator, col_name)
|
|
32
|
+
elif isinstance(validator, Regex):
|
|
33
|
+
_validate_regex(series, validator, col_name)
|
|
34
|
+
elif isinstance(validator, MinLen):
|
|
35
|
+
_validate_minlen(series, validator, col_name)
|
|
36
|
+
elif isinstance(validator, MaxLen):
|
|
37
|
+
_validate_maxlen(series, validator, col_name)
|
|
38
|
+
else:
|
|
39
|
+
raise ValidationError(f"Unknown validator type: {type(validator)}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _get_invalid_samples(series: pd.Series, invalid_mask: pd.Series) -> tuple[list[tuple], int]:
|
|
43
|
+
"""
|
|
44
|
+
Extract invalid samples and total count from an invalid mask.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
series: pandas Series being validated
|
|
48
|
+
invalid_mask: Boolean mask indicating invalid values
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Tuple of (samples, total_invalid) where samples is a list of (index, value) tuples
|
|
52
|
+
"""
|
|
53
|
+
invalid_indices = series.index[invalid_mask][:MAX_SAMPLE_SIZE]
|
|
54
|
+
samples = [(idx, series.loc[idx]) for idx in invalid_indices]
|
|
55
|
+
total_invalid = invalid_mask.sum()
|
|
56
|
+
return samples, total_invalid
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _validate_range(series: pd.Series, validator: Range, col_name: str) -> None:
|
|
60
|
+
"""Validate that all values in series are within the specified range."""
|
|
61
|
+
invalid_mask = (series < validator.min) | (series > validator.max)
|
|
62
|
+
if not invalid_mask.any():
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
66
|
+
raise ValidationError.new_with_samples(
|
|
67
|
+
col_name,
|
|
68
|
+
f"values must be in range [{validator.min}, {validator.max}]",
|
|
69
|
+
samples,
|
|
70
|
+
total_invalid,
|
|
71
|
+
format_value=str,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _validate_unique(series: pd.Series, col_name: str) -> None:
|
|
76
|
+
"""Validate that all values in series are unique (no duplicates)."""
|
|
77
|
+
duplicated_mask = series.duplicated(keep=False)
|
|
78
|
+
if not duplicated_mask.any():
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
samples, total_invalid = _get_invalid_samples(series, duplicated_mask)
|
|
82
|
+
raise ValidationError.new_with_samples(
|
|
83
|
+
col_name,
|
|
84
|
+
"contains duplicate values",
|
|
85
|
+
samples,
|
|
86
|
+
total_invalid,
|
|
87
|
+
format_value=repr,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _validate_in(series: pd.Series, validator: In, col_name: str) -> None:
|
|
92
|
+
"""Validate that all values in series are within the allowed set."""
|
|
93
|
+
invalid_mask = ~series.isin(validator.allowed_values)
|
|
94
|
+
if not invalid_mask.any():
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
98
|
+
raise ValidationError.new_with_samples(
|
|
99
|
+
col_name, "contains values not in allowed values", samples, total_invalid
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _validate_regex(series: pd.Series, validator: Regex, col_name: str) -> None:
|
|
104
|
+
"""Validate that all values in series match the regex pattern."""
|
|
105
|
+
invalid_mask = ~series.str.match(validator.pattern)
|
|
106
|
+
if not invalid_mask.any():
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
110
|
+
raise ValidationError.new_with_samples(
|
|
111
|
+
col_name, "contains values that don't match the pattern", samples, total_invalid
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _validate_minlen(series: pd.Series, validator: MinLen, col_name: str) -> None:
|
|
116
|
+
"""Validate that all string values have minimum length."""
|
|
117
|
+
invalid_mask = series.str.len() < validator.min_length
|
|
118
|
+
if not invalid_mask.any():
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
122
|
+
raise ValidationError.new_with_samples(
|
|
123
|
+
col_name,
|
|
124
|
+
"contains strings shorter than minimum length",
|
|
125
|
+
samples,
|
|
126
|
+
total_invalid,
|
|
127
|
+
format_value=lambda val: f"{repr(val)} (length: {len(val)})",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _validate_maxlen(series: pd.Series, validator: MaxLen, col_name: str) -> None:
|
|
132
|
+
"""Validate that all string values have maximum length."""
|
|
133
|
+
invalid_mask = series.str.len() > validator.max_length
|
|
134
|
+
if not invalid_mask.any():
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
138
|
+
raise ValidationError.new_with_samples(
|
|
139
|
+
col_name,
|
|
140
|
+
"contains strings longer than maximum length",
|
|
141
|
+
samples,
|
|
142
|
+
total_invalid,
|
|
143
|
+
format_value=lambda val: f"{repr(val)} (length: {len(val)})",
|
|
144
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Polars-specific implementation details."""
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Common validation functions for Polars DataFrame schema checking."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import date, datetime, timedelta
|
|
5
|
+
from typing import Annotated, Callable, Union, get_args, get_origin, get_type_hints
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import polars as pl
|
|
9
|
+
except ImportError:
|
|
10
|
+
raise ImportError("Polars is not installed. Install it with: pip install pavise[polars]")
|
|
11
|
+
|
|
12
|
+
from pavise.exceptions import ValidationError
|
|
13
|
+
|
|
14
|
+
# Maximum number of invalid sample values to show in error messages
|
|
15
|
+
MAX_SAMPLE_SIZE = 5
|
|
16
|
+
# Maximum number of rows to check for type validation (performance optimization)
|
|
17
|
+
MAX_CHECK_ROWS = 100
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class TypeChecker:
|
|
22
|
+
"""Type checker with both dtype-level and value-level validation."""
|
|
23
|
+
|
|
24
|
+
dtype: Callable # Check dtype
|
|
25
|
+
value: Callable[[object], bool] # Check individual values
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_datetime_dtype(dtype):
|
|
29
|
+
"""Check if dtype is a Datetime type (with any time unit)."""
|
|
30
|
+
if dtype == pl.Datetime:
|
|
31
|
+
return True
|
|
32
|
+
if hasattr(dtype, "time_unit"):
|
|
33
|
+
return True
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
TYPE_CHECKERS = {
|
|
38
|
+
int: TypeChecker(
|
|
39
|
+
dtype=lambda dtype: dtype
|
|
40
|
+
in (pl.Int8, pl.Int16, pl.Int32, pl.Int64, pl.UInt8, pl.UInt16, pl.UInt32, pl.UInt64),
|
|
41
|
+
value=lambda x: isinstance(x, int) and not isinstance(x, bool),
|
|
42
|
+
),
|
|
43
|
+
float: TypeChecker(
|
|
44
|
+
dtype=lambda dtype: dtype in (pl.Float32, pl.Float64),
|
|
45
|
+
value=lambda x: isinstance(x, (int, float)) and not isinstance(x, bool),
|
|
46
|
+
),
|
|
47
|
+
str: TypeChecker(
|
|
48
|
+
dtype=lambda dtype: dtype == pl.Utf8,
|
|
49
|
+
value=lambda x: isinstance(x, str),
|
|
50
|
+
),
|
|
51
|
+
bool: TypeChecker(
|
|
52
|
+
dtype=lambda dtype: dtype == pl.Boolean,
|
|
53
|
+
value=lambda x: isinstance(x, bool),
|
|
54
|
+
),
|
|
55
|
+
datetime: TypeChecker(
|
|
56
|
+
dtype=_is_datetime_dtype,
|
|
57
|
+
value=lambda x: isinstance(x, datetime),
|
|
58
|
+
),
|
|
59
|
+
date: TypeChecker(
|
|
60
|
+
dtype=lambda dtype: dtype == pl.Date,
|
|
61
|
+
value=lambda x: isinstance(x, date),
|
|
62
|
+
),
|
|
63
|
+
timedelta: TypeChecker(
|
|
64
|
+
dtype=lambda dtype: dtype == pl.Duration,
|
|
65
|
+
value=lambda x: isinstance(x, timedelta),
|
|
66
|
+
),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def validate_dataframe(df: pl.DataFrame, schema: type) -> None:
|
|
71
|
+
"""
|
|
72
|
+
Validate that a Polars DataFrame conforms to a Protocol schema.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
df: Polars DataFrame to validate
|
|
76
|
+
schema: Protocol type defining the expected schema
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ValueError: If a required column is missing or type is unsupported
|
|
80
|
+
TypeError: If a column has the wrong type
|
|
81
|
+
"""
|
|
82
|
+
expected_cols = get_type_hints(schema, include_extras=True)
|
|
83
|
+
|
|
84
|
+
for col_name, col_type in expected_cols.items():
|
|
85
|
+
_check_column_exists(df, col_name)
|
|
86
|
+
_check_column_type(df, col_name, col_type)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _extract_type_and_validators(annotation: type) -> tuple[type, list, bool]:
|
|
90
|
+
"""
|
|
91
|
+
Extract base type, validators, and nullable flag from a type annotation.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
annotation: Type annotation (e.g., int, Optional[int], or Annotated[int, Range(0, 100)])
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Tuple of (base_type, validators, is_optional)
|
|
98
|
+
- For Annotated[int, Range(0, 100)]: (int, [Range(0, 100)], False)
|
|
99
|
+
- For int: (int, [], False)
|
|
100
|
+
- For Optional[int]: (int, [], True)
|
|
101
|
+
- For Annotated[Optional[int], Range(0, 100)]: (int, [Range(0, 100)], True)
|
|
102
|
+
"""
|
|
103
|
+
validators = []
|
|
104
|
+
is_optional = False
|
|
105
|
+
|
|
106
|
+
if get_origin(annotation) is Annotated:
|
|
107
|
+
args = get_args(annotation)
|
|
108
|
+
base_type = args[0]
|
|
109
|
+
validators = list(args[1:])
|
|
110
|
+
annotation = base_type
|
|
111
|
+
|
|
112
|
+
origin = get_origin(annotation)
|
|
113
|
+
if origin is Union:
|
|
114
|
+
args = get_args(annotation)
|
|
115
|
+
if len(args) == 2 and type(None) in args:
|
|
116
|
+
is_optional = True
|
|
117
|
+
base_type = args[0] if args[1] is type(None) else args[1]
|
|
118
|
+
return base_type, validators, is_optional
|
|
119
|
+
|
|
120
|
+
return annotation, validators, is_optional
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _raise_type_error_with_samples(
|
|
124
|
+
df: pl.DataFrame, col_name: str, checker: TypeChecker, expected_type: type, actual_dtype
|
|
125
|
+
) -> None:
|
|
126
|
+
"""Raise TypeError with sample invalid values."""
|
|
127
|
+
invalid_mask = df[col_name].map_elements(lambda v: not checker.value(v))
|
|
128
|
+
invalid_df = df[col_name].to_frame().with_row_index("__row__").filter(invalid_mask)
|
|
129
|
+
samples = [
|
|
130
|
+
(row["__row__"], row[col_name])
|
|
131
|
+
for row in invalid_df.head(MAX_SAMPLE_SIZE).iter_rows(named=True)
|
|
132
|
+
]
|
|
133
|
+
total_invalid = int(invalid_mask.sum())
|
|
134
|
+
|
|
135
|
+
raise ValidationError.new_with_samples(
|
|
136
|
+
col_name,
|
|
137
|
+
f"expected {expected_type.__name__}, got {actual_dtype}",
|
|
138
|
+
samples,
|
|
139
|
+
total_invalid,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _check_column_exists(df: pl.DataFrame, col_name: str) -> None:
|
|
144
|
+
"""Check if a column exists in the DataFrame."""
|
|
145
|
+
if col_name not in df.columns:
|
|
146
|
+
raise ValidationError("missing", column_name=col_name)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _check_column_type(df: pl.DataFrame, col_name: str, expected_type: type) -> None:
|
|
150
|
+
"""Check if a column has the expected type and apply validators."""
|
|
151
|
+
from pavise._polars.validator_impl import apply_validator
|
|
152
|
+
|
|
153
|
+
base_type, validators, is_optional = _extract_type_and_validators(expected_type)
|
|
154
|
+
|
|
155
|
+
if isinstance(base_type, type) and issubclass(base_type, pl.DataType):
|
|
156
|
+
col_dtype = df[col_name].dtype
|
|
157
|
+
if col_dtype != base_type:
|
|
158
|
+
raise ValidationError(
|
|
159
|
+
f"expected {base_type.__name__}, got {col_dtype}",
|
|
160
|
+
column_name=col_name,
|
|
161
|
+
)
|
|
162
|
+
for validator in validators:
|
|
163
|
+
apply_validator(df[col_name], validator, col_name)
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
if base_type not in TYPE_CHECKERS:
|
|
167
|
+
raise ValidationError(f"unsupported type: {base_type}", column_name=col_name)
|
|
168
|
+
|
|
169
|
+
checker = TYPE_CHECKERS[base_type]
|
|
170
|
+
col_dtype = df[col_name].dtype
|
|
171
|
+
if not checker.dtype(col_dtype):
|
|
172
|
+
_raise_type_error_with_samples(df, col_name, checker, base_type, col_dtype)
|
|
173
|
+
|
|
174
|
+
if not is_optional and df[col_name].null_count() > 0:
|
|
175
|
+
raise ValidationError("is non-optional but contains null values", column_name=col_name)
|
|
176
|
+
|
|
177
|
+
for validator in validators:
|
|
178
|
+
apply_validator(df[col_name], validator, col_name)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Polars-specific validator implementations."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import polars as pl
|
|
7
|
+
except ImportError:
|
|
8
|
+
raise ImportError("Polars is not installed. Install it with: pip install pavise[polars]")
|
|
9
|
+
|
|
10
|
+
from pavise.exceptions import ValidationError
|
|
11
|
+
from pavise.validators import In, MaxLen, MinLen, Range, Regex, Unique
|
|
12
|
+
|
|
13
|
+
# Maximum number of invalid sample values to show in error messages
|
|
14
|
+
MAX_SAMPLE_SIZE = 5
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def apply_validator(series: "pl.Series", validator: Any, col_name: str) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Apply a validator to a polars Series.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
series: polars Series to validate
|
|
23
|
+
validator: Validator instance (e.g., Range, Unique, In, Regex, MinLen, MaxLen)
|
|
24
|
+
col_name: column name for error messages
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
ValueError: if validation fails
|
|
28
|
+
"""
|
|
29
|
+
if isinstance(validator, Range):
|
|
30
|
+
_validate_range(series, validator, col_name)
|
|
31
|
+
elif isinstance(validator, Unique):
|
|
32
|
+
_validate_unique(series, col_name)
|
|
33
|
+
elif isinstance(validator, In):
|
|
34
|
+
_validate_in(series, validator, col_name)
|
|
35
|
+
elif isinstance(validator, Regex):
|
|
36
|
+
_validate_regex(series, validator, col_name)
|
|
37
|
+
elif isinstance(validator, MinLen):
|
|
38
|
+
_validate_minlen(series, validator, col_name)
|
|
39
|
+
elif isinstance(validator, MaxLen):
|
|
40
|
+
_validate_maxlen(series, validator, col_name)
|
|
41
|
+
else:
|
|
42
|
+
raise ValidationError(f"Unknown validator type: {type(validator)}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _get_invalid_samples(series: "pl.Series", invalid_mask: "pl.Series") -> tuple[list[tuple], int]:
|
|
46
|
+
"""
|
|
47
|
+
Extract invalid samples and total count from an invalid mask.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
series: polars Series being validated
|
|
51
|
+
invalid_mask: Boolean mask indicating invalid values
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
Tuple of (samples, total_invalid) where samples is a list of (index, value) tuples
|
|
55
|
+
"""
|
|
56
|
+
invalid_df = series.to_frame().with_row_index("__row__").filter(invalid_mask)
|
|
57
|
+
samples = [
|
|
58
|
+
(row["__row__"], row[series.name])
|
|
59
|
+
for row in invalid_df.head(MAX_SAMPLE_SIZE).iter_rows(named=True)
|
|
60
|
+
]
|
|
61
|
+
total_invalid = int(invalid_mask.sum())
|
|
62
|
+
return samples, total_invalid
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _validate_range(series: "pl.Series", validator: Range, col_name: str) -> None:
|
|
66
|
+
"""Validate that all values in series are within the specified range."""
|
|
67
|
+
invalid_mask = (series < validator.min) | (series > validator.max)
|
|
68
|
+
if not invalid_mask.any():
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
72
|
+
raise ValidationError.new_with_samples(
|
|
73
|
+
col_name,
|
|
74
|
+
f"values must be in range [{validator.min}, {validator.max}]",
|
|
75
|
+
samples,
|
|
76
|
+
total_invalid,
|
|
77
|
+
format_value=str,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _validate_unique(series: "pl.Series", col_name: str) -> None:
|
|
82
|
+
"""Validate that all values in series are unique (no duplicates)."""
|
|
83
|
+
duplicated_mask = series.is_duplicated()
|
|
84
|
+
if not duplicated_mask.any():
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
samples, total_invalid = _get_invalid_samples(series, duplicated_mask)
|
|
88
|
+
raise ValidationError.new_with_samples(
|
|
89
|
+
col_name,
|
|
90
|
+
"contains duplicate values",
|
|
91
|
+
samples,
|
|
92
|
+
total_invalid=total_invalid,
|
|
93
|
+
format_value=repr,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _validate_in(series: "pl.Series", validator: In, col_name: str) -> None:
|
|
98
|
+
"""Validate that all values in series are within the allowed set."""
|
|
99
|
+
invalid_mask = ~series.is_in(validator.allowed_values)
|
|
100
|
+
if not invalid_mask.any():
|
|
101
|
+
return
|
|
102
|
+
|
|
103
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
104
|
+
raise ValidationError.new_with_samples(
|
|
105
|
+
col_name, "contains values not in allowed values", samples, total_invalid
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _validate_regex(series: "pl.Series", validator: Regex, col_name: str) -> None:
|
|
110
|
+
"""Validate that all values in series match the regex pattern."""
|
|
111
|
+
invalid_mask = ~series.str.contains(f"^{validator.pattern}$")
|
|
112
|
+
if not invalid_mask.any():
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
116
|
+
raise ValidationError.new_with_samples(
|
|
117
|
+
col_name, "contains values that don't match the pattern", samples, total_invalid
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _validate_minlen(series: "pl.Series", validator: MinLen, col_name: str) -> None:
|
|
122
|
+
"""Validate that all string values have minimum length."""
|
|
123
|
+
invalid_mask = series.str.len_chars() < validator.min_length
|
|
124
|
+
if not invalid_mask.any():
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
128
|
+
raise ValidationError.new_with_samples(
|
|
129
|
+
col_name,
|
|
130
|
+
"contains strings shorter than minimum length",
|
|
131
|
+
samples,
|
|
132
|
+
total_invalid,
|
|
133
|
+
format_value=lambda val: f"{repr(val)} (length: {len(val)})",
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _validate_maxlen(series: "pl.Series", validator: MaxLen, col_name: str) -> None:
|
|
138
|
+
"""Validate that all string values have maximum length."""
|
|
139
|
+
invalid_mask = series.str.len_chars() > validator.max_length
|
|
140
|
+
if not invalid_mask.any():
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
samples, total_invalid = _get_invalid_samples(series, invalid_mask)
|
|
144
|
+
raise ValidationError.new_with_samples(
|
|
145
|
+
col_name,
|
|
146
|
+
"contains strings longer than maximum length",
|
|
147
|
+
samples,
|
|
148
|
+
total_invalid,
|
|
149
|
+
format_value=lambda val: f"{repr(val)} (length: {len(val)})",
|
|
150
|
+
)
|
pavise/exceptions.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Custom exceptions for patrol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable
|
|
6
|
+
|
|
7
|
+
from typing_extensions import Self
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PatrolError(Exception):
|
|
11
|
+
"""Base exception for all patrol errors."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ValidationError(PatrolError):
|
|
17
|
+
"""
|
|
18
|
+
Raised when DataFrame validation fails.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
message: Human-readable error message
|
|
22
|
+
column_name: Name of the column that failed validation (if applicable)
|
|
23
|
+
invalid_samples: List of (row_index, value) tuples showing sample invalid values
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
base_message: str,
|
|
29
|
+
column_name: str | None = None,
|
|
30
|
+
invalid_samples: list[tuple] | None = None,
|
|
31
|
+
):
|
|
32
|
+
msg = base_message
|
|
33
|
+
if column_name:
|
|
34
|
+
msg = f"Column '{column_name}': {msg}"
|
|
35
|
+
super().__init__(msg)
|
|
36
|
+
self.column_name = column_name
|
|
37
|
+
self.invalid_samples = invalid_samples or []
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def new_with_samples(
|
|
41
|
+
cls,
|
|
42
|
+
col_name: str,
|
|
43
|
+
base_message: str,
|
|
44
|
+
samples: list[tuple],
|
|
45
|
+
total_invalid: int,
|
|
46
|
+
format_value: Callable[[Any], str] = repr,
|
|
47
|
+
) -> Self:
|
|
48
|
+
"""
|
|
49
|
+
Create a ValidationError with a formatted message including sample invalid values.
|
|
50
|
+
Args:
|
|
51
|
+
col_name: Column name
|
|
52
|
+
base_message: Base error message (e.g., "values must be in range [0, 150]")
|
|
53
|
+
samples: List of (index, value) tuples
|
|
54
|
+
total_invalid: Total number of invalid values
|
|
55
|
+
format_value: Optional function to format values (default: repr)
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Formatted error message
|
|
59
|
+
"""
|
|
60
|
+
msg = base_message
|
|
61
|
+
msg += f"\n\nSample invalid values (showing first {len(samples)} of {total_invalid}):"
|
|
62
|
+
msg += "".join([f"\n Row {idx}: {format_value(val)}" for idx, val in samples])
|
|
63
|
+
return cls(msg, column_name=col_name, invalid_samples=samples)
|
pavise/pandas.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Pandas backend for type-parameterized DataFrame with Protocol-based schema validation."""
|
|
2
|
+
|
|
3
|
+
from typing import Generic, Optional, TypeVar
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from pavise._pandas.validation import validate_dataframe
|
|
8
|
+
|
|
9
|
+
SchemaT_co = TypeVar("SchemaT_co", covariant=True)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DataFrame(pd.DataFrame, Generic[SchemaT_co]):
|
|
13
|
+
"""
|
|
14
|
+
Type-parameterized DataFrame with runtime validation for pandas.
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
# Static type checking only
|
|
18
|
+
def process(df: DataFrame[UserSchema]) -> DataFrame[UserSchema]:
|
|
19
|
+
return df
|
|
20
|
+
|
|
21
|
+
# Runtime validation
|
|
22
|
+
validated = DataFrame[UserSchema](raw_df)
|
|
23
|
+
|
|
24
|
+
The type parameter is covariant, allowing structural subtyping:
|
|
25
|
+
DataFrame[ChildSchema] is compatible with DataFrame[ParentSchema]
|
|
26
|
+
when ChildSchema has all columns of ParentSchema.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
_schema: Optional[type] = None
|
|
30
|
+
|
|
31
|
+
def __class_getitem__(cls, schema: type):
|
|
32
|
+
"""Create a new DataFrame class with schema validation."""
|
|
33
|
+
|
|
34
|
+
class TypedDataFrame(DataFrame):
|
|
35
|
+
_schema = schema
|
|
36
|
+
|
|
37
|
+
return TypedDataFrame
|
|
38
|
+
|
|
39
|
+
def __init__(self, data, *args, **kwargs):
|
|
40
|
+
"""
|
|
41
|
+
Initialize DataFrame with optional schema validation.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
data: Data to create DataFrame from
|
|
45
|
+
*args: Additional arguments passed to pd.DataFrame
|
|
46
|
+
**kwargs: Additional keyword arguments passed to pd.DataFrame
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
ValueError: If required column is missing
|
|
50
|
+
TypeError: If column has wrong type
|
|
51
|
+
"""
|
|
52
|
+
pd.DataFrame.__init__(self, data, *args, **kwargs) # type: ignore[misc]
|
|
53
|
+
if self._schema is not None:
|
|
54
|
+
validate_dataframe(self, self._schema)
|
pavise/polars.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Polars backend for type-parameterized DataFrame with Protocol-based schema validation."""
|
|
2
|
+
|
|
3
|
+
from typing import Generic, Optional, TypeVar
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import polars as pl
|
|
7
|
+
except ImportError:
|
|
8
|
+
raise ImportError("Polars is not installed. Install it with: pip install pavise[polars]")
|
|
9
|
+
|
|
10
|
+
from pavise._polars.validation import validate_dataframe
|
|
11
|
+
|
|
12
|
+
SchemaT_co = TypeVar("SchemaT_co", covariant=True)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DataFrame(pl.DataFrame, Generic[SchemaT_co]):
|
|
16
|
+
"""
|
|
17
|
+
Type-parameterized DataFrame with runtime validation for Polars.
|
|
18
|
+
|
|
19
|
+
Usage:
|
|
20
|
+
# Static type checking only
|
|
21
|
+
def process(df: DataFrame[UserSchema]) -> DataFrame[UserSchema]:
|
|
22
|
+
return df
|
|
23
|
+
|
|
24
|
+
# Runtime validation
|
|
25
|
+
validated = DataFrame[UserSchema](raw_df)
|
|
26
|
+
|
|
27
|
+
The type parameter is covariant, allowing structural subtyping:
|
|
28
|
+
DataFrame[ChildSchema] is compatible with DataFrame[ParentSchema]
|
|
29
|
+
when ChildSchema has all columns of ParentSchema.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
_schema: Optional[type] = None
|
|
33
|
+
|
|
34
|
+
def __class_getitem__(cls, schema: type):
|
|
35
|
+
"""Create a new DataFrame class with schema validation."""
|
|
36
|
+
|
|
37
|
+
class TypedDataFrame(DataFrame):
|
|
38
|
+
_schema = schema
|
|
39
|
+
|
|
40
|
+
return TypedDataFrame
|
|
41
|
+
|
|
42
|
+
def __init__(self, data, *args, **kwargs):
|
|
43
|
+
"""
|
|
44
|
+
Initialize DataFrame with optional schema validation.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
data: Data to create DataFrame from (pl.DataFrame or dict/list)
|
|
48
|
+
*args: Additional arguments passed to pl.DataFrame
|
|
49
|
+
**kwargs: Additional keyword arguments passed to pl.DataFrame
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
ValueError: If required column is missing
|
|
53
|
+
TypeError: If column has wrong type
|
|
54
|
+
"""
|
|
55
|
+
pl.DataFrame.__init__(self, data, *args, **kwargs) # type: ignore[misc]
|
|
56
|
+
if self._schema is not None:
|
|
57
|
+
validate_dataframe(self, self._schema)
|
pavise/validators.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Validators for DataFrame column validation with Annotated types.
|
|
2
|
+
|
|
3
|
+
Validators are simple data classes that define validation rules.
|
|
4
|
+
The actual validation logic is implemented in backend-specific modules:
|
|
5
|
+
- _pandas.validator_impl for pandas
|
|
6
|
+
- _polars.validator_impl for polars
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Range:
|
|
14
|
+
"""Validate that numeric values are within a specified range.
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
age: Annotated[int, Range(0, 150)]
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
min: float
|
|
21
|
+
max: float
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Unique:
|
|
26
|
+
"""Validate that column values are unique (no duplicates).
|
|
27
|
+
|
|
28
|
+
Example:
|
|
29
|
+
user_id: Annotated[int, Unique()]
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class In:
|
|
35
|
+
"""Validate that column values are within a set of allowed values.
|
|
36
|
+
|
|
37
|
+
Example:
|
|
38
|
+
status: Annotated[str, In(["pending", "approved", "rejected"])]
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
allowed_values: list
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Regex:
|
|
46
|
+
r"""Validate that string values match a regular expression pattern.
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
email: Annotated[str, Regex(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')]
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
pattern: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class MinLen:
|
|
57
|
+
"""Validate that string values have a minimum length.
|
|
58
|
+
|
|
59
|
+
Example:
|
|
60
|
+
username: Annotated[str, MinLen(3)]
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
min_length: int
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class MaxLen:
|
|
68
|
+
"""Validate that string values have a maximum length.
|
|
69
|
+
|
|
70
|
+
Example:
|
|
71
|
+
username: Annotated[str, MaxLen(20)]
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
max_length: int
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pavise
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: DataFrame validation library using Python Protocol for structural subtyping
|
|
5
|
+
Author: kitagry
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Requires-Dist: typing-extensions>=4.0.0
|
|
9
|
+
Provides-Extra: all
|
|
10
|
+
Requires-Dist: pandas>=1.3.0; extra == 'all'
|
|
11
|
+
Requires-Dist: polars>=0.15.0; extra == 'all'
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pandas>=1.3.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: polars>=0.15.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: pyrefly>=0.1.0; extra == 'dev'
|
|
16
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
|
|
17
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
18
|
+
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
19
|
+
Requires-Dist: tox>=4.0.0; extra == 'dev'
|
|
20
|
+
Provides-Extra: pandas
|
|
21
|
+
Requires-Dist: pandas>=1.3.0; extra == 'pandas'
|
|
22
|
+
Provides-Extra: polars
|
|
23
|
+
Requires-Dist: polars>=0.15.0; extra == 'polars'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Pavise
|
|
27
|
+
|
|
28
|
+
DataFrame validation library using Python Protocol for structural subtyping.
|
|
29
|
+
|
|
30
|
+
## Features
|
|
31
|
+
|
|
32
|
+
- Use Python Protocol to define DataFrame schemas
|
|
33
|
+
- `DataFrame[Schema]` type annotation for static type checking
|
|
34
|
+
- Structural subtyping: validate only required columns, ignore extra columns
|
|
35
|
+
- Covariant type parameters: `DataFrame[ChildSchema]` is compatible with `DataFrame[ParentSchema]`
|
|
36
|
+
- Optional runtime validation
|
|
37
|
+
- No inheritance required
|
|
38
|
+
- Support for both pandas and polars backends
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# For pandas support
|
|
44
|
+
pip install pavise[pandas]
|
|
45
|
+
|
|
46
|
+
# For polars support
|
|
47
|
+
pip install pavise[polars]
|
|
48
|
+
|
|
49
|
+
# For both
|
|
50
|
+
pip install pavise[all]
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
### Pandas Backend
|
|
56
|
+
|
|
57
|
+
#### Static Type Checking Only (Recommended)
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from typing import Protocol
|
|
61
|
+
from pavise.pandas import DataFrame
|
|
62
|
+
|
|
63
|
+
class UserSchema(Protocol):
|
|
64
|
+
name: str
|
|
65
|
+
age: int
|
|
66
|
+
|
|
67
|
+
def process_users(df: DataFrame[UserSchema]) -> DataFrame[UserSchema]:
|
|
68
|
+
# mypy/pyrefly will check types, no runtime validation
|
|
69
|
+
return df[df['age'] >= 18]
|
|
70
|
+
|
|
71
|
+
# Use regular pandas DataFrame
|
|
72
|
+
import pandas as pd
|
|
73
|
+
df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 17]})
|
|
74
|
+
result = process_users(df)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### Runtime Validation (Explicit)
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from typing import Protocol
|
|
81
|
+
import pandas as pd
|
|
82
|
+
from pavise.pandas import DataFrame
|
|
83
|
+
|
|
84
|
+
class UserSchema(Protocol):
|
|
85
|
+
name: str
|
|
86
|
+
age: int
|
|
87
|
+
|
|
88
|
+
def load_users(raw_df: pd.DataFrame) -> DataFrame[UserSchema]:
|
|
89
|
+
# Validate at runtime when needed
|
|
90
|
+
return DataFrame[UserSchema](raw_df)
|
|
91
|
+
|
|
92
|
+
raw_df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 17]})
|
|
93
|
+
validated_df = load_users(raw_df) # Runtime validation occurs here
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Polars Backend
|
|
97
|
+
|
|
98
|
+
#### Static Type Checking Only (Recommended)
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from typing import Protocol
|
|
102
|
+
from pavise.polars import DataFrame
|
|
103
|
+
|
|
104
|
+
class UserSchema(Protocol):
|
|
105
|
+
name: str
|
|
106
|
+
age: int
|
|
107
|
+
|
|
108
|
+
def process_users(df: DataFrame[UserSchema]) -> DataFrame[UserSchema]:
|
|
109
|
+
# mypy/pyrefly will check types, no runtime validation
|
|
110
|
+
return df.filter(df['age'] >= 18)
|
|
111
|
+
|
|
112
|
+
# Use regular polars DataFrame
|
|
113
|
+
import polars as pl
|
|
114
|
+
df = pl.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 17]})
|
|
115
|
+
result = process_users(df)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
#### Runtime Validation (Explicit)
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from typing import Protocol
|
|
122
|
+
import polars as pl
|
|
123
|
+
from pavise.polars import DataFrame
|
|
124
|
+
|
|
125
|
+
class UserSchema(Protocol):
|
|
126
|
+
name: str
|
|
127
|
+
age: int
|
|
128
|
+
|
|
129
|
+
def load_users(raw_df: pl.DataFrame) -> DataFrame[UserSchema]:
|
|
130
|
+
# Validate at runtime when needed
|
|
131
|
+
return DataFrame[UserSchema](raw_df)
|
|
132
|
+
|
|
133
|
+
raw_df = pl.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 17]})
|
|
134
|
+
validated_df = load_users(raw_df) # Runtime validation occurs here
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Structural Subtyping
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from typing import Protocol
|
|
141
|
+
import pandas as pd
|
|
142
|
+
from pavise.pandas import DataFrame
|
|
143
|
+
|
|
144
|
+
class UserSchema(Protocol):
|
|
145
|
+
name: str
|
|
146
|
+
|
|
147
|
+
class UserWithEmailSchema(Protocol):
|
|
148
|
+
name: str
|
|
149
|
+
email: str
|
|
150
|
+
|
|
151
|
+
def process_user(df: DataFrame[UserSchema]) -> None:
|
|
152
|
+
print(df['name'])
|
|
153
|
+
|
|
154
|
+
# This works! UserWithEmailSchema has all required columns of UserSchema
|
|
155
|
+
df: DataFrame[UserWithEmailSchema] = pd.DataFrame({
|
|
156
|
+
'name': ['Alice'],
|
|
157
|
+
'email': ['alice@example.com']
|
|
158
|
+
})
|
|
159
|
+
process_user(df) # OK - covariant type parameter
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Extra Columns are Ignored
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from typing import Protocol
|
|
166
|
+
import pandas as pd
|
|
167
|
+
from pavise.pandas import DataFrame
|
|
168
|
+
|
|
169
|
+
class SimpleSchema(Protocol):
|
|
170
|
+
a: int
|
|
171
|
+
|
|
172
|
+
# Extra columns are ignored during validation
|
|
173
|
+
df = pd.DataFrame({
|
|
174
|
+
'a': [1, 2, 3],
|
|
175
|
+
'b': ['x', 'y', 'z'], # Extra column - ignored
|
|
176
|
+
'c': [10.0, 20.0, 30.0] # Extra column - ignored
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
validated = DataFrame[SimpleSchema](df) # OK
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Supported Types
|
|
183
|
+
|
|
184
|
+
- `int`
|
|
185
|
+
- `float`
|
|
186
|
+
- `str`
|
|
187
|
+
- `bool`
|
|
188
|
+
|
|
189
|
+
## Development
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
# Install with dev dependencies (includes both pandas and polars)
|
|
193
|
+
uv pip install -e ".[dev]"
|
|
194
|
+
|
|
195
|
+
# Run all tests
|
|
196
|
+
uv run pytest
|
|
197
|
+
|
|
198
|
+
# Run tests for specific backend
|
|
199
|
+
uv run pytest tests/test_pandas.py
|
|
200
|
+
uv run pytest tests/test_polars.py
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Testing with tox
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
# Run tests for all Python versions and backends
|
|
207
|
+
tox
|
|
208
|
+
|
|
209
|
+
# Run tests for specific environment
|
|
210
|
+
tox -e py312-pandas # Test pandas backend with Python 3.12
|
|
211
|
+
tox -e py312-polars # Test polars backend with Python 3.12
|
|
212
|
+
tox -e py312-all # Test both backends with Python 3.12
|
|
213
|
+
|
|
214
|
+
# Run linting
|
|
215
|
+
tox -e lint
|
|
216
|
+
|
|
217
|
+
# Run type checking
|
|
218
|
+
tox -e type
|
|
219
|
+
|
|
220
|
+
# Available Python versions: py39, py310, py311, py312
|
|
221
|
+
# Available backends: pandas, polars, all
|
|
222
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
pavise/__init__.py,sha256=kLj98t1AifJaSVYaup5frQkAgdt8GhL11DAtX6kjUNQ,127
|
|
2
|
+
pavise/exceptions.py,sha256=QSKi5c_yuXEhXq4IxJFO5L0CU8a7tWHoITm0a18KJ04,1943
|
|
3
|
+
pavise/pandas.py,sha256=MUgDW1p4zjUD42wiTIlWfTYQBxZ-k9I0SXVC8om9ryY,1708
|
|
4
|
+
pavise/polars.py,sha256=Fukv37IIA3J1h7teA5t5ygTncHjQoky1f332tpvpo_E,1859
|
|
5
|
+
pavise/validators.py,sha256=PlJeVfRnIblSBavrnwpwoH9v_h9VyIUXkM0bQMQeBK4,1446
|
|
6
|
+
pavise/_pandas/__init__.py,sha256=7O2Oa_lT6jDNKbrSmXPYtnfpFFarUN-j2InWUaUZl7k,46
|
|
7
|
+
pavise/_pandas/validation.py,sha256=KfG1Vt9K8z0x4Nxsx34I3KyV2AWV3yUc6kCzAUrPJj0,10425
|
|
8
|
+
pavise/_pandas/validator_impl.py,sha256=prgxhUx_bKwIWz3xPk50pARmrpHcDU8E6Xoawk8ad_Q,5005
|
|
9
|
+
pavise/_polars/__init__.py,sha256=C3E88FTFonWIDFyonQcLV9G0qIP0-aCzQMi2GjrKDWg,46
|
|
10
|
+
pavise/_polars/validation.py,sha256=mgN1xTfJwnRVxxh0THjxFRuZi1VADcgClc2d-jIEv_A,6092
|
|
11
|
+
pavise/_polars/validator_impl.py,sha256=6QNhb-UhAp6MVkkO4PFyXqmBp64cNgo0yxPu48r2UMs,5269
|
|
12
|
+
pavise-0.0.1.dist-info/METADATA,sha256=WlSu6sPmk7lHNEfBsaS8Hs1JTSZt7mIKtHYGgZdkB_g,5225
|
|
13
|
+
pavise-0.0.1.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
14
|
+
pavise-0.0.1.dist-info/RECORD,,
|