sparkenforce 0.1.0__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.
@@ -0,0 +1,450 @@
1
+ """
2
+ sparkenforce: Type validation for PySpark DataFrames.
3
+
4
+ This module provides a Dataset type annotation system that allows you to specify
5
+ and validate the schema of PySpark DataFrames using Python type hints for both
6
+ function arguments and return values.
7
+
8
+ Example:
9
+ @validate
10
+ def process_data(df: Dataset["id": int, "name": str, "age": int]) -> Dataset["result": str]:
11
+ # Function will validate that df has the required columns and types
12
+ # Return value will also be validated against the specified schema
13
+ return spark.createDataFrame([("processed",)], ["result"])
14
+
15
+ Apache Software License 2.0
16
+
17
+ Copyright (c) 2025, Agustín Recoba
18
+
19
+ Licensed under the Apache License, Version 2.0 (the "License");
20
+ you may not use this file except in compliance with the License.
21
+ You may obtain a copy of the License at
22
+
23
+ http://www.apache.org/licenses/LICENSE-2.0
24
+
25
+ Unless required by applicable law or agreed to in writing, software
26
+ distributed under the License is distributed on an "AS IS" BASIS,
27
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
+ See the License for the specific language governing permissions and
29
+ limitations under the License.
30
+ """
31
+
32
+ import datetime
33
+ import decimal
34
+ import inspect
35
+ from functools import wraps
36
+ from typing import Any, Dict, Set, Tuple, Type, TypeVar, get_type_hints
37
+
38
+ from pyspark.sql import DataFrame
39
+ from pyspark.sql import types as spark_types
40
+
41
+ __all__ = ["Dataset", "DatasetValidationError", "validate"]
42
+
43
+
44
+ class DatasetValidationError(TypeError):
45
+ """Raised when DataFrame validation fails."""
46
+
47
+
48
+ T = TypeVar("T", bound=callable)
49
+
50
+
51
+ def validate(func: T) -> T:
52
+ """
53
+ Decorator that validates function arguments and return values annotated with Dataset types.
54
+
55
+ Args:
56
+ func: Function to decorate with validation
57
+
58
+ Returns:
59
+ Wrapped function with validation logic
60
+
61
+ Raises:
62
+ DatasetValidationError: When validation fails
63
+
64
+ Example:
65
+ @validate
66
+ def process(data: Dataset["id", "name"]) -> Dataset["result": str]:
67
+ return spark.createDataFrame([("success",)], ["result"])
68
+ """
69
+ signature = inspect.signature(func)
70
+ hints = get_type_hints(func)
71
+
72
+ @wraps(func)
73
+ def wrapper(*args, **kwargs):
74
+ bound = signature.bind(*args, **kwargs)
75
+
76
+ # Validate input arguments
77
+ for argument_name, value in bound.arguments.items():
78
+ if argument_name in hints and isinstance(
79
+ hints[argument_name],
80
+ _DatasetMeta,
81
+ ):
82
+ hint = hints[argument_name]
83
+ _validate_dataframe(value, hint, argument_name)
84
+
85
+ # Execute the function
86
+ result = func(*args, **kwargs)
87
+
88
+ # Validate return value if annotated with Dataset type
89
+ return_annotation = hints.get("return")
90
+ if return_annotation is not None and isinstance(
91
+ return_annotation,
92
+ _DatasetMeta,
93
+ ):
94
+ _validate_dataframe(result, return_annotation, "return value")
95
+
96
+ return result
97
+
98
+ return wrapper
99
+
100
+
101
+ def _validate_dataframe(
102
+ value: object, hint: "_DatasetMeta", argument_name: str
103
+ ) -> None:
104
+ """
105
+ Validate a single DataFrame against a Dataset hint.
106
+
107
+ Args:
108
+ value: Value to validate
109
+ hint: Dataset metadata with validation rules
110
+ argument_name: Name of the argument being validated
111
+
112
+ Raises:
113
+ DatasetValidationError: When validation fails
114
+ """
115
+ if not isinstance(value, DataFrame):
116
+ raise DatasetValidationError(
117
+ f"{argument_name} must be a PySpark DataFrame, got {type(value)}"
118
+ )
119
+
120
+ columns = set(value.columns)
121
+
122
+ # Check column presence
123
+ if hint.only_specified and columns != hint.columns:
124
+ missing = hint.columns - columns
125
+ extra = columns - hint.columns
126
+ msg_parts = []
127
+ if missing:
128
+ msg_parts.append(f"missing columns: {missing}")
129
+ if extra:
130
+ msg_parts.append(f"unexpected columns: {extra}")
131
+ raise DatasetValidationError(
132
+ f"{argument_name} columns mismatch. Expected exactly {hint.columns}, "
133
+ f"got {columns}. {', '.join(msg_parts)}"
134
+ )
135
+
136
+ if not hint.only_specified and not hint.columns.issubset(columns):
137
+ missing = hint.columns - columns
138
+ raise DatasetValidationError(
139
+ f"{argument_name} is missing required columns: {missing}"
140
+ )
141
+
142
+ # Check data types
143
+ if hint.dtypes:
144
+ _validate_dtypes(value, hint.dtypes, argument_name)
145
+
146
+
147
+ def _validate_dtypes(
148
+ df: DataFrame,
149
+ expected_dtypes: Dict[str, Any],
150
+ argument_name: str,
151
+ ) -> None:
152
+ """
153
+ Validate DataFrame column types.
154
+
155
+ Args:
156
+ df: DataFrame to validate
157
+ expected_dtypes: Expected column types
158
+ argument_name: Name of the argument being validated
159
+
160
+ Raises:
161
+ DatasetValidationError: When type validation fails
162
+ """
163
+ actual_dtypes = dict(df.dtypes)
164
+
165
+ for col_name, expected_type in expected_dtypes.items():
166
+ if col_name not in actual_dtypes:
167
+ continue # Column presence already validated
168
+
169
+ actual_type_str = actual_dtypes[col_name]
170
+ actual_spark_type = spark_types.DataType.fromDDL(actual_type_str)
171
+
172
+ # Convert expected type to Spark type
173
+ expected_spark_type = _convert_to_spark_type(expected_type)
174
+
175
+ if not _types_compatible(actual_spark_type, expected_spark_type):
176
+ raise DatasetValidationError(
177
+ f"{argument_name} column '{col_name}' has incorrect type. "
178
+ f"Expected {expected_type}, got {type(actual_spark_type).__name__}"
179
+ )
180
+
181
+
182
+ def _convert_to_spark_type(python_type: Any) -> Type[spark_types.DataType]:
183
+ """
184
+ Convert Python type to Spark DataType.
185
+
186
+ Args:
187
+ python_type: Python type to convert
188
+
189
+ Returns:
190
+ Corresponding Spark DataType class
191
+
192
+ Raises:
193
+ TypeError: When python_type is not a supported type
194
+ """
195
+ if isinstance(python_type, type) and issubclass(python_type, spark_types.DataType):
196
+ return python_type
197
+
198
+ if python_type in spark_types._type_mappings:
199
+ return spark_types._type_mappings[python_type]
200
+
201
+ # Explicit mapping for common types
202
+ type_mapping = {
203
+ type(None): spark_types.NullType,
204
+ bool: spark_types.BooleanType,
205
+ int: spark_types.LongType,
206
+ float: spark_types.DoubleType,
207
+ str: spark_types.StringType,
208
+ bytearray: spark_types.BinaryType,
209
+ decimal.Decimal: spark_types.DecimalType,
210
+ datetime.date: spark_types.DateType,
211
+ datetime.datetime: spark_types.TimestampType,
212
+ datetime.time: spark_types.TimestampType,
213
+ }
214
+
215
+ if python_type in type_mapping:
216
+ return type_mapping[python_type]
217
+
218
+ # Raise error for unsupported types instead of silent fallback
219
+ supported_types = list(type_mapping.keys())
220
+ raise TypeError(
221
+ f"Unsupported type for Dataset column validation: {python_type}. "
222
+ f"Supported types are: {', '.join(str(t) for t in supported_types)} "
223
+ f"or any subclass of pyspark.sql.types.DataType"
224
+ )
225
+
226
+
227
+ def _types_compatible(
228
+ actual: spark_types.DataType, expected: Type[spark_types.DataType]
229
+ ) -> bool:
230
+ """
231
+ Check if actual Spark type is compatible with expected type.
232
+
233
+ Args:
234
+ actual: Actual Spark DataType instance
235
+ expected: Expected Spark DataType class
236
+
237
+ Returns:
238
+ True if types are compatible
239
+ """
240
+ # Direct type match
241
+ if isinstance(actual, expected):
242
+ return True
243
+
244
+ # Define compatible type groups for more flexible validation
245
+ integer_types = (
246
+ spark_types.IntegerType,
247
+ spark_types.LongType,
248
+ spark_types.ShortType,
249
+ spark_types.ByteType,
250
+ )
251
+ float_types = (spark_types.FloatType, spark_types.DoubleType)
252
+ string_types = (spark_types.StringType,)
253
+ timestamp_types = (spark_types.TimestampType, spark_types.DateType)
254
+
255
+ # Check if actual and expected types are in the same compatibility group
256
+ compatibility_groups = [integer_types, float_types, string_types, timestamp_types]
257
+
258
+ return any(
259
+ isinstance(actual, group) and expected in group
260
+ for group in compatibility_groups
261
+ )
262
+
263
+
264
+ def _get_columns_dtypes(parameters: Any) -> Tuple[Set[str], Dict[str, Any]]:
265
+ """
266
+ Extract column names and types from Dataset parameters.
267
+
268
+ Args:
269
+ parameters: Dataset parameters to parse
270
+
271
+ Returns:
272
+ Tuple of (column_names, column_types)
273
+
274
+ Raises:
275
+ TypeError: When parameters are invalid or types are unsupported
276
+ """
277
+ columns: Set[str] = set()
278
+ dtypes: Dict[str, Any] = {}
279
+
280
+ if isinstance(parameters, str):
281
+ columns.add(parameters)
282
+ elif isinstance(parameters, slice):
283
+ if not isinstance(parameters.start, str):
284
+ raise TypeError("Column name must be a string")
285
+ columns.add(parameters.start)
286
+ if parameters.stop is not None:
287
+ # Validate the type early to catch unsupported types
288
+ try:
289
+ _convert_to_spark_type(parameters.stop)
290
+ except TypeError as e:
291
+ # Re-raise with more context about where the error occurred
292
+ raise TypeError(
293
+ f"Invalid type for column '{parameters.start}': {str(e)}"
294
+ ) from e
295
+ dtypes[parameters.start] = parameters.stop
296
+ elif isinstance(parameters, (list, tuple, set)):
297
+ for element in parameters:
298
+ sub_columns, sub_dtypes = _get_columns_dtypes(element)
299
+ columns.update(sub_columns)
300
+ dtypes.update(sub_dtypes)
301
+ elif isinstance(parameters, _DatasetMeta):
302
+ columns.update(parameters.columns)
303
+ dtypes.update(parameters.dtypes)
304
+ else:
305
+ raise TypeError(
306
+ f"Dataset parameters must be strings, slices, lists, or DatasetMeta instances. "
307
+ f"Got {type(parameters)}"
308
+ )
309
+
310
+ return columns, dtypes
311
+
312
+
313
+ class _DatasetMeta(type):
314
+ """
315
+ Metaclass for Dataset type annotations.
316
+
317
+ This metaclass handles the creation of Dataset types with column and type specifications.
318
+ """
319
+
320
+ only_specified: bool
321
+ columns: Set[str]
322
+ dtypes: Dict[str, Any]
323
+
324
+ def __getitem__(cls, parameters: object) -> "_DatasetMeta":
325
+ """
326
+ Create a Dataset type with specified columns and types.
327
+
328
+ Args:
329
+ parameters: Column specifications (strings, slices, lists, etc.)
330
+
331
+ Returns:
332
+ New DatasetMeta instance with validation rules
333
+
334
+ Example:
335
+ Dataset["id", "name"] # Exact columns
336
+ Dataset["id": int, "name": str] # With types
337
+ Dataset["id", "name", ...] # Minimum columns
338
+ """
339
+ if not isinstance(parameters, tuple):
340
+ parameters = (parameters,)
341
+
342
+ parameters = list(parameters)
343
+
344
+ # Check for ellipsis (indicates minimum columns, not exact match)
345
+ only_specified = True
346
+ if parameters and parameters[-1] is Ellipsis:
347
+ only_specified = False
348
+ parameters.pop()
349
+
350
+ columns, dtypes = _get_columns_dtypes(parameters)
351
+
352
+ # Create new metaclass instance
353
+ meta = _DatasetMeta(
354
+ cls.__name__,
355
+ cls.__bases__ if hasattr(cls, "__bases__") else (),
356
+ {},
357
+ )
358
+ meta.only_specified = only_specified
359
+ meta.columns = columns
360
+ meta.dtypes = dtypes
361
+
362
+ return meta
363
+
364
+ def __repr__(cls) -> str:
365
+ """String representation of Dataset type."""
366
+ if hasattr(cls, "dtypes") and cls.dtypes:
367
+ type_strs = [
368
+ f"{col}: {dt.__name__ if hasattr(dt, '__name__') else str(dt)}"
369
+ for col, dt in cls.dtypes.items()
370
+ ]
371
+ return f"Dataset[{', '.join(type_strs)}]"
372
+
373
+ if hasattr(cls, "columns") and cls.columns:
374
+ return f"Dataset[{', '.join(sorted(cls.columns))}]"
375
+
376
+ return "Dataset"
377
+
378
+
379
+ class Dataset(DataFrame, metaclass=_DatasetMeta):
380
+ """
381
+ Type annotation for PySpark DataFrames with schema validation.
382
+
383
+ Dataset cannot be instantiated directly. It serves as a type annotation
384
+ to specify the expected schema of DataFrames passed to functions and
385
+ returned from functions.
386
+
387
+ Examples:
388
+ Dataset["id", "name"] # Exact columns required
389
+ Dataset["id": int, "name": str] # With type checking
390
+ Dataset["id", "name", ...] # Minimum columns (can have more)
391
+ Dataset[...] # Any DataFrame
392
+
393
+ Usage:
394
+ @validate
395
+ def process_users(users: Dataset["id": int, "name": str]) -> Dataset["result": str]:
396
+ # users is guaranteed to have 'id' (int) and 'name' (str) columns
397
+ # return value will be validated to have 'result' (str) column
398
+ return spark.createDataFrame([("success",)], ["result"])
399
+ """
400
+
401
+ __slots__ = ()
402
+
403
+ def __new__(cls, *args, **kwargs):
404
+ """Prevent direct instantiation."""
405
+ raise TypeError(
406
+ "Dataset cannot be instantiated directly. "
407
+ "Use spark.createDataFrame() to create DataFrames, "
408
+ "and use Dataset[...] for type annotations only."
409
+ )
410
+
411
+
412
+ def infer_dataset_type(df: DataFrame) -> str:
413
+ """
414
+ Infer a Dataset[...] annotation string from a PySpark DataFrame's schema.
415
+
416
+ Args:
417
+ df: The PySpark DataFrame to inspect.
418
+
419
+ Returns:
420
+ A string representing the Dataset annotation, e.g.:
421
+ 'Dataset["id": int, "name": str]'
422
+ """
423
+ spark_to_py = {
424
+ spark_types.StringType: str,
425
+ spark_types.BooleanType: bool,
426
+ spark_types.ByteType: int,
427
+ spark_types.ShortType: int,
428
+ spark_types.IntegerType: int,
429
+ spark_types.LongType: int,
430
+ spark_types.FloatType: float,
431
+ spark_types.DoubleType: float,
432
+ spark_types.DecimalType: decimal.Decimal,
433
+ spark_types.DateType: datetime.date,
434
+ spark_types.TimestampType: datetime.datetime,
435
+ spark_types.BinaryType: bytearray,
436
+ spark_types.NullType: type(None),
437
+ }
438
+ fields = []
439
+ for field in df.schema.fields:
440
+ py_type = None
441
+ for spark_type, candidate_py in spark_to_py.items():
442
+ if isinstance(field.dataType, spark_type):
443
+ py_type = candidate_py
444
+ break
445
+ if py_type is None:
446
+ py_type = type(field.dataType) # fallback to Spark type class
447
+ fields.append(
448
+ f'"{field.name}": {py_type.__name__ if hasattr(py_type, "__name__") else str(py_type)}',
449
+ )
450
+ return f'Dataset[{", ".join(fields)}]'
@@ -0,0 +1,382 @@
1
+ Metadata-Version: 2.4
2
+ Name: sparkenforce
3
+ Version: 0.1.0
4
+ Summary: Type annotation system that allows you to specify and validate the schema of PySpark DataFrames using Python type hints for both function arguments and return values.
5
+ Project-URL: homepage, https://github.com/agustin-recoba/sparkenforce
6
+ Project-URL: repository, https://github.com/agustin-recoba/sparkenforce.git
7
+ Project-URL: documentation, https://github.com/agustin-recoba/sparkenforce
8
+ Project-URL: issues, https://github.com/agustin-recoba/sparkenforce/issues
9
+ Author-email: Agustín Recoba <agustin.recoba@outlook.com>
10
+ License: Apache Software License 2.0
11
+
12
+ Copyright (c) 2025, Agustín Recoba
13
+
14
+ Licensed under the Apache License, Version 2.0 (the "License");
15
+ you may not use this file except in compliance with the License.
16
+ You may obtain a copy of the License at
17
+
18
+ http://www.apache.org/licenses/LICENSE-2.0
19
+
20
+ Unless required by applicable law or agreed to in writing, software
21
+ distributed under the License is distributed on an "AS IS" BASIS,
22
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ See the License for the specific language governing permissions and
24
+ limitations under the License.
25
+
26
+
27
+ Original License, part of the original proyect "dataenforce" (`https://github.com/CedricFR/dataenforce`)
28
+
29
+ Apache License
30
+ Version 2.0, January 2004
31
+ http://www.apache.org/licenses/
32
+
33
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
34
+
35
+ 1. Definitions.
36
+
37
+ "License" shall mean the terms and conditions for use, reproduction,
38
+ and distribution as defined by Sections 1 through 9 of this document.
39
+
40
+ "Licensor" shall mean the copyright owner or entity authorized by
41
+ the copyright owner that is granting the License.
42
+
43
+ "Legal Entity" shall mean the union of the acting entity and all
44
+ other entities that control, are controlled by, or are under common
45
+ control with that entity. For the purposes of this definition,
46
+ "control" means (i) the power, direct or indirect, to cause the
47
+ direction or management of such entity, whether by contract or
48
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
49
+ outstanding shares, or (iii) beneficial ownership of such entity.
50
+
51
+ "You" (or "Your") shall mean an individual or Legal Entity
52
+ exercising permissions granted by this License.
53
+
54
+ "Source" form shall mean the preferred form for making modifications,
55
+ including but not limited to software source code, documentation
56
+ source, and configuration files.
57
+
58
+ "Object" form shall mean any form resulting from mechanical
59
+ transformation or translation of a Source form, including but
60
+ not limited to compiled object code, generated documentation,
61
+ and conversions to other media types.
62
+
63
+ "Work" shall mean the work of authorship, whether in Source or
64
+ Object form, made available under the License, as indicated by a
65
+ copyright notice that is included in or attached to the work
66
+ (an example is provided in the Appendix below).
67
+
68
+ "Derivative Works" shall mean any work, whether in Source or Object
69
+ form, that is based on (or derived from) the Work and for which the
70
+ editorial revisions, annotations, elaborations, or other modifications
71
+ represent, as a whole, an original work of authorship. For the purposes
72
+ of this License, Derivative Works shall not include works that remain
73
+ separable from, or merely link (or bind by name) to the interfaces of,
74
+ the Work and Derivative Works thereof.
75
+
76
+ "Contribution" shall mean any work of authorship, including
77
+ the original version of the Work and any modifications or additions
78
+ to that Work or Derivative Works thereof, that is intentionally
79
+ submitted to Licensor for inclusion in the Work by the copyright owner
80
+ or by an individual or Legal Entity authorized to submit on behalf of
81
+ the copyright owner. For the purposes of this definition, "submitted"
82
+ means any form of electronic, verbal, or written communication sent
83
+ to the Licensor or its representatives, including but not limited to
84
+ communication on electronic mailing lists, source code control systems,
85
+ and issue tracking systems that are managed by, or on behalf of, the
86
+ Licensor for the purpose of discussing and improving the Work, but
87
+ excluding communication that is conspicuously marked or otherwise
88
+ designated in writing by the copyright owner as "Not a Contribution."
89
+
90
+ "Contributor" shall mean Licensor and any individual or Legal Entity
91
+ on behalf of whom a Contribution has been received by Licensor and
92
+ subsequently incorporated within the Work.
93
+
94
+ 2. Grant of Copyright License. Subject to the terms and conditions of
95
+ this License, each Contributor hereby grants to You a perpetual,
96
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
97
+ copyright license to reproduce, prepare Derivative Works of,
98
+ publicly display, publicly perform, sublicense, and distribute the
99
+ Work and such Derivative Works in Source or Object form.
100
+
101
+ 3. Grant of Patent License. Subject to the terms and conditions of
102
+ this License, each Contributor hereby grants to You a perpetual,
103
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
104
+ (except as stated in this section) patent license to make, have made,
105
+ use, offer to sell, sell, import, and otherwise transfer the Work,
106
+ where such license applies only to those patent claims licensable
107
+ by such Contributor that are necessarily infringed by their
108
+ Contribution(s) alone or by combination of their Contribution(s)
109
+ with the Work to which such Contribution(s) was submitted. If You
110
+ institute patent litigation against any entity (including a
111
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
112
+ or a Contribution incorporated within the Work constitutes direct
113
+ or contributory patent infringement, then any patent licenses
114
+ granted to You under this License for that Work shall terminate
115
+ as of the date such litigation is filed.
116
+
117
+ 4. Redistribution. You may reproduce and distribute copies of the
118
+ Work or Derivative Works thereof in any medium, with or without
119
+ modifications, and in Source or Object form, provided that You
120
+ meet the following conditions:
121
+
122
+ (a) You must give any other recipients of the Work or
123
+ Derivative Works a copy of this License; and
124
+
125
+ (b) You must cause any modified files to carry prominent notices
126
+ stating that You changed the files; and
127
+
128
+ (c) You must retain, in the Source form of any Derivative Works
129
+ that You distribute, all copyright, patent, trademark, and
130
+ attribution notices from the Source form of the Work,
131
+ excluding those notices that do not pertain to any part of
132
+ the Derivative Works; and
133
+
134
+ (d) If the Work includes a "NOTICE" text file as part of its
135
+ distribution, then any Derivative Works that You distribute must
136
+ include a readable copy of the attribution notices contained
137
+ within such NOTICE file, excluding those notices that do not
138
+ pertain to any part of the Derivative Works, in at least one
139
+ of the following places: within a NOTICE text file distributed
140
+ as part of the Derivative Works; within the Source form or
141
+ documentation, if provided along with the Derivative Works; or,
142
+ within a display generated by the Derivative Works, if and
143
+ wherever such third-party notices normally appear. The contents
144
+ of the NOTICE file are for informational purposes only and
145
+ do not modify the License. You may add Your own attribution
146
+ notices within Derivative Works that You distribute, alongside
147
+ or as an addendum to the NOTICE text from the Work, provided
148
+ that such additional attribution notices cannot be construed
149
+ as modifying the License.
150
+
151
+ You may add Your own copyright statement to Your modifications and
152
+ may provide additional or different license terms and conditions
153
+ for use, reproduction, or distribution of Your modifications, or
154
+ for any such Derivative Works as a whole, provided Your use,
155
+ reproduction, and distribution of the Work otherwise complies with
156
+ the conditions stated in this License.
157
+
158
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
159
+ any Contribution intentionally submitted for inclusion in the Work
160
+ by You to the Licensor shall be under the terms and conditions of
161
+ this License, without any additional terms or conditions.
162
+ Notwithstanding the above, nothing herein shall supersede or modify
163
+ the terms of any separate license agreement you may have executed
164
+ with Licensor regarding such Contributions.
165
+
166
+ 6. Trademarks. This License does not grant permission to use the trade
167
+ names, trademarks, service marks, or product names of the Licensor,
168
+ except as required for reasonable and customary use in describing the
169
+ origin of the Work and reproducing the content of the NOTICE file.
170
+
171
+ 7. Disclaimer of Warranty. Unless required by applicable law or
172
+ agreed to in writing, Licensor provides the Work (and each
173
+ Contributor provides its Contributions) on an "AS IS" BASIS,
174
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
175
+ implied, including, without limitation, any warranties or conditions
176
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
177
+ PARTICULAR PURPOSE. You are solely responsible for determining the
178
+ appropriateness of using or redistributing the Work and assume any
179
+ risks associated with Your exercise of permissions under this License.
180
+
181
+ 8. Limitation of Liability. In no event and under no legal theory,
182
+ whether in tort (including negligence), contract, or otherwise,
183
+ unless required by applicable law (such as deliberate and grossly
184
+ negligent acts) or agreed to in writing, shall any Contributor be
185
+ liable to You for damages, including any direct, indirect, special,
186
+ incidental, or consequential damages of any character arising as a
187
+ result of this License or out of the use or inability to use the
188
+ Work (including but not limited to damages for loss of goodwill,
189
+ work stoppage, computer failure or malfunction, or any and all
190
+ other commercial damages or losses), even if such Contributor
191
+ has been advised of the possibility of such damages.
192
+
193
+ 9. Accepting Warranty or Additional Liability. While redistributing
194
+ the Work or Derivative Works thereof, You may choose to offer,
195
+ and charge a fee for, acceptance of support, warranty, indemnity,
196
+ or other liability obligations and/or rights consistent with this
197
+ License. However, in accepting such obligations, You may act only
198
+ on Your own behalf and on Your sole responsibility, not on behalf
199
+ of any other Contributor, and only if You agree to indemnify,
200
+ defend, and hold each Contributor harmless for any liability
201
+ incurred by, or claims asserted against, such Contributor by reason
202
+ of your accepting any such warranty or additional liability.
203
+
204
+ END OF TERMS AND CONDITIONS
205
+
206
+ APPENDIX: How to apply the Apache License to your work.
207
+
208
+ To apply the Apache License to your work, attach the following
209
+ boilerplate notice, with the fields enclosed by brackets "[]"
210
+ replaced with your own identifying information. (Don't include
211
+ the brackets!) The text should be enclosed in the appropriate
212
+ comment syntax for the file format. We also recommend that a
213
+ file or class name and description of purpose be included on the
214
+ same "printed page" as the copyright notice for easier
215
+ identification within third-party archives.
216
+
217
+ Copyright [yyyy] [name of copyright owner]
218
+
219
+ Licensed under the Apache License, Version 2.0 (the "License");
220
+ you may not use this file except in compliance with the License.
221
+ You may obtain a copy of the License at
222
+
223
+ http://www.apache.org/licenses/LICENSE-2.0
224
+
225
+ Unless required by applicable law or agreed to in writing, software
226
+ distributed under the License is distributed on an "AS IS" BASIS,
227
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
228
+ See the License for the specific language governing permissions and
229
+ limitations under the License.
230
+ License-File: LICENSE
231
+ Keywords: python
232
+ Classifier: Development Status :: 4 - Beta
233
+ Classifier: Programming Language :: Python
234
+ Classifier: Programming Language :: Python :: 3
235
+ Classifier: Programming Language :: Python :: 3.10
236
+ Classifier: Programming Language :: Python :: 3.11
237
+ Classifier: Programming Language :: Python :: 3.12
238
+ Classifier: Programming Language :: Python :: 3.13
239
+ Classifier: Typing :: Typed
240
+ Requires-Python: <4,>=3.10
241
+ Requires-Dist: pyspark>=3.0.0
242
+ Description-Content-Type: text/markdown
243
+
244
+ # :rocket: sparkenforce
245
+
246
+ **sparkenforce** is a type annotation system that lets you specify and validate PySpark DataFrame schemas using Python type hints. It validates both function arguments and return values, catching schema mismatches before they cause runtime errors.
247
+
248
+ ## Why sparkenforce?
249
+
250
+ Working with PySpark DataFrames can be error-prone when schemas don't match expectations. sparkenforce helps by:
251
+
252
+ - **Preventing runtime errors**: Catch schema mismatches early with type validation
253
+ - **Improving code clarity**: Function signatures show exactly what DataFrame structure is expected
254
+ - **Enforcing contracts**: Ensure functions return DataFrames with the promised schema
255
+ - **Better debugging**: Clear error messages when validations fail
256
+
257
+ ## Installation
258
+
259
+ Install sparkenforce using pip:
260
+
261
+ ```bash
262
+ pip install sparkenforce
263
+ ```
264
+
265
+ Or if you're using uv:
266
+
267
+ ```bash
268
+ uv add sparkenforce
269
+ ```
270
+
271
+ ## Quick Start
272
+
273
+ ### Validating Input DataFrames
274
+
275
+ ```python
276
+ import sparkenforce
277
+ from pyspark.sql import functions as F
278
+
279
+ @sparkenforce.validate
280
+ def transform_data(df: sparkenforce.Dataset['firstname':str, ...]) -> sparkenforce.Dataset['name':str, 'length':int]:
281
+ """Transform DataFrame with validated input and output schemas."""
282
+ return df.select(
283
+ df.firstname.alias('name'),
284
+ F.length(df.firstname).alias('length')
285
+ )
286
+
287
+ # If input DataFrame doesn't have 'firstname' column, validation fails
288
+ # If return DataFrame doesn't match expected schema, validation fails
289
+ ```
290
+
291
+ ### Flexible Schemas with Ellipsis
292
+
293
+ Use `...` to allow additional columns beyond the specified ones:
294
+
295
+ ```python
296
+ @sparkenforce.validate
297
+ def process_names(df: sparkenforce.Dataset['firstname':str, 'lastname':str, ...]):
298
+ """Requires firstname and lastname, but allows other columns too."""
299
+ return df.filter(df.firstname != "")
300
+ ```
301
+
302
+ ### Return Value Validation
303
+
304
+ sparkenforce validates that your function returns exactly what you promise:
305
+
306
+ ```python
307
+ @sparkenforce.validate
308
+ def get_summary(df: sparkenforce.Dataset['firstname':str, ...]) -> sparkenforce.Dataset['firstname':str, 'summary':str, ...]:
309
+ return df.select(
310
+ 'firstname',
311
+ F.lit('processed').alias('summary'),
312
+ 'lastname' # Additional columns allowed with ...
313
+ )
314
+ ```
315
+
316
+ ## Error Handling
317
+
318
+ When validation fails, sparkenforce provides clear error messages:
319
+
320
+ ```python
321
+ # This will raise DatasetValidationError with detailed message:
322
+ # "return value columns mismatch. Expected exactly {'name', 'length'},
323
+ # got {'lastname', 'firstname'}. missing columns: {'name', 'length'},
324
+ # unexpected columns: {'lastname', 'firstname'}"
325
+
326
+ @sparkenforce.validate
327
+ def bad_function(df: sparkenforce.Dataset['firstname':str, ...]) -> sparkenforce.Dataset['name':str, 'length':int]:
328
+ return df.select('firstname', 'lastname') # Wrong columns!
329
+ ```
330
+
331
+
332
+ ## Development Setup
333
+
334
+ **Step 1**: Create virtual environment
335
+ ```bash
336
+ uv venv
337
+ ```
338
+
339
+ **Step 2**: Activate environment
340
+ ```bash
341
+ # Linux/Mac
342
+ source .venv/bin/activate
343
+
344
+ # Windows
345
+ .venv\Scripts\activate
346
+ ```
347
+
348
+ **Step 3**: Install dependencies
349
+ ```bash
350
+ uv sync
351
+ ```
352
+
353
+ ## CLI Commands
354
+
355
+ ```bash
356
+ # Run tests
357
+ task tests
358
+
359
+ # Type checking
360
+ task type
361
+
362
+ # Linting
363
+ task lint
364
+
365
+ # Format code
366
+ task format
367
+
368
+ # Coverage report
369
+ task coverage
370
+ ```
371
+
372
+ ## Inspiration
373
+
374
+ This project builds on [dataenforce](https://github.com/CedricFR/dataenforce), extending it with additional validation capabilities for PySpark DataFrame workflows.
375
+
376
+ ## License
377
+
378
+ Apache Software License v2.0
379
+
380
+ ## Contact
381
+
382
+ Created by [Agustín Recoba](https://github.com/agustin-recoba)
@@ -0,0 +1,5 @@
1
+ sparkenforce/__init__.py,sha256=nV36EXw-zQ4U3W9TEWqvf8lYxrw5gBceuMcnDoQGntw,15008
2
+ sparkenforce-0.1.0.dist-info/METADATA,sha256=G8UQFZlvmJuaLbt2pQin6jG1wpVIP18qabRJHkuPMyc,17326
3
+ sparkenforce-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
+ sparkenforce-0.1.0.dist-info/licenses/LICENSE,sha256=vLd3j3I_iOtcGExnlBC84DFUAOkkD9p-hDhPZQps6b4,10949
5
+ sparkenforce-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,220 @@
1
+ Apache Software License 2.0
2
+
3
+ Copyright (c) 2025, Agustín Recoba
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+
18
+ Original License, part of the original proyect "dataenforce" (`https://github.com/CedricFR/dataenforce`)
19
+
20
+ Apache License
21
+ Version 2.0, January 2004
22
+ http://www.apache.org/licenses/
23
+
24
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
25
+
26
+ 1. Definitions.
27
+
28
+ "License" shall mean the terms and conditions for use, reproduction,
29
+ and distribution as defined by Sections 1 through 9 of this document.
30
+
31
+ "Licensor" shall mean the copyright owner or entity authorized by
32
+ the copyright owner that is granting the License.
33
+
34
+ "Legal Entity" shall mean the union of the acting entity and all
35
+ other entities that control, are controlled by, or are under common
36
+ control with that entity. For the purposes of this definition,
37
+ "control" means (i) the power, direct or indirect, to cause the
38
+ direction or management of such entity, whether by contract or
39
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
40
+ outstanding shares, or (iii) beneficial ownership of such entity.
41
+
42
+ "You" (or "Your") shall mean an individual or Legal Entity
43
+ exercising permissions granted by this License.
44
+
45
+ "Source" form shall mean the preferred form for making modifications,
46
+ including but not limited to software source code, documentation
47
+ source, and configuration files.
48
+
49
+ "Object" form shall mean any form resulting from mechanical
50
+ transformation or translation of a Source form, including but
51
+ not limited to compiled object code, generated documentation,
52
+ and conversions to other media types.
53
+
54
+ "Work" shall mean the work of authorship, whether in Source or
55
+ Object form, made available under the License, as indicated by a
56
+ copyright notice that is included in or attached to the work
57
+ (an example is provided in the Appendix below).
58
+
59
+ "Derivative Works" shall mean any work, whether in Source or Object
60
+ form, that is based on (or derived from) the Work and for which the
61
+ editorial revisions, annotations, elaborations, or other modifications
62
+ represent, as a whole, an original work of authorship. For the purposes
63
+ of this License, Derivative Works shall not include works that remain
64
+ separable from, or merely link (or bind by name) to the interfaces of,
65
+ the Work and Derivative Works thereof.
66
+
67
+ "Contribution" shall mean any work of authorship, including
68
+ the original version of the Work and any modifications or additions
69
+ to that Work or Derivative Works thereof, that is intentionally
70
+ submitted to Licensor for inclusion in the Work by the copyright owner
71
+ or by an individual or Legal Entity authorized to submit on behalf of
72
+ the copyright owner. For the purposes of this definition, "submitted"
73
+ means any form of electronic, verbal, or written communication sent
74
+ to the Licensor or its representatives, including but not limited to
75
+ communication on electronic mailing lists, source code control systems,
76
+ and issue tracking systems that are managed by, or on behalf of, the
77
+ Licensor for the purpose of discussing and improving the Work, but
78
+ excluding communication that is conspicuously marked or otherwise
79
+ designated in writing by the copyright owner as "Not a Contribution."
80
+
81
+ "Contributor" shall mean Licensor and any individual or Legal Entity
82
+ on behalf of whom a Contribution has been received by Licensor and
83
+ subsequently incorporated within the Work.
84
+
85
+ 2. Grant of Copyright License. Subject to the terms and conditions of
86
+ this License, each Contributor hereby grants to You a perpetual,
87
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
88
+ copyright license to reproduce, prepare Derivative Works of,
89
+ publicly display, publicly perform, sublicense, and distribute the
90
+ Work and such Derivative Works in Source or Object form.
91
+
92
+ 3. Grant of Patent License. Subject to the terms and conditions of
93
+ this License, each Contributor hereby grants to You a perpetual,
94
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
95
+ (except as stated in this section) patent license to make, have made,
96
+ use, offer to sell, sell, import, and otherwise transfer the Work,
97
+ where such license applies only to those patent claims licensable
98
+ by such Contributor that are necessarily infringed by their
99
+ Contribution(s) alone or by combination of their Contribution(s)
100
+ with the Work to which such Contribution(s) was submitted. If You
101
+ institute patent litigation against any entity (including a
102
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
103
+ or a Contribution incorporated within the Work constitutes direct
104
+ or contributory patent infringement, then any patent licenses
105
+ granted to You under this License for that Work shall terminate
106
+ as of the date such litigation is filed.
107
+
108
+ 4. Redistribution. You may reproduce and distribute copies of the
109
+ Work or Derivative Works thereof in any medium, with or without
110
+ modifications, and in Source or Object form, provided that You
111
+ meet the following conditions:
112
+
113
+ (a) You must give any other recipients of the Work or
114
+ Derivative Works a copy of this License; and
115
+
116
+ (b) You must cause any modified files to carry prominent notices
117
+ stating that You changed the files; and
118
+
119
+ (c) You must retain, in the Source form of any Derivative Works
120
+ that You distribute, all copyright, patent, trademark, and
121
+ attribution notices from the Source form of the Work,
122
+ excluding those notices that do not pertain to any part of
123
+ the Derivative Works; and
124
+
125
+ (d) If the Work includes a "NOTICE" text file as part of its
126
+ distribution, then any Derivative Works that You distribute must
127
+ include a readable copy of the attribution notices contained
128
+ within such NOTICE file, excluding those notices that do not
129
+ pertain to any part of the Derivative Works, in at least one
130
+ of the following places: within a NOTICE text file distributed
131
+ as part of the Derivative Works; within the Source form or
132
+ documentation, if provided along with the Derivative Works; or,
133
+ within a display generated by the Derivative Works, if and
134
+ wherever such third-party notices normally appear. The contents
135
+ of the NOTICE file are for informational purposes only and
136
+ do not modify the License. You may add Your own attribution
137
+ notices within Derivative Works that You distribute, alongside
138
+ or as an addendum to the NOTICE text from the Work, provided
139
+ that such additional attribution notices cannot be construed
140
+ as modifying the License.
141
+
142
+ You may add Your own copyright statement to Your modifications and
143
+ may provide additional or different license terms and conditions
144
+ for use, reproduction, or distribution of Your modifications, or
145
+ for any such Derivative Works as a whole, provided Your use,
146
+ reproduction, and distribution of the Work otherwise complies with
147
+ the conditions stated in this License.
148
+
149
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
150
+ any Contribution intentionally submitted for inclusion in the Work
151
+ by You to the Licensor shall be under the terms and conditions of
152
+ this License, without any additional terms or conditions.
153
+ Notwithstanding the above, nothing herein shall supersede or modify
154
+ the terms of any separate license agreement you may have executed
155
+ with Licensor regarding such Contributions.
156
+
157
+ 6. Trademarks. This License does not grant permission to use the trade
158
+ names, trademarks, service marks, or product names of the Licensor,
159
+ except as required for reasonable and customary use in describing the
160
+ origin of the Work and reproducing the content of the NOTICE file.
161
+
162
+ 7. Disclaimer of Warranty. Unless required by applicable law or
163
+ agreed to in writing, Licensor provides the Work (and each
164
+ Contributor provides its Contributions) on an "AS IS" BASIS,
165
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
166
+ implied, including, without limitation, any warranties or conditions
167
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
168
+ PARTICULAR PURPOSE. You are solely responsible for determining the
169
+ appropriateness of using or redistributing the Work and assume any
170
+ risks associated with Your exercise of permissions under this License.
171
+
172
+ 8. Limitation of Liability. In no event and under no legal theory,
173
+ whether in tort (including negligence), contract, or otherwise,
174
+ unless required by applicable law (such as deliberate and grossly
175
+ negligent acts) or agreed to in writing, shall any Contributor be
176
+ liable to You for damages, including any direct, indirect, special,
177
+ incidental, or consequential damages of any character arising as a
178
+ result of this License or out of the use or inability to use the
179
+ Work (including but not limited to damages for loss of goodwill,
180
+ work stoppage, computer failure or malfunction, or any and all
181
+ other commercial damages or losses), even if such Contributor
182
+ has been advised of the possibility of such damages.
183
+
184
+ 9. Accepting Warranty or Additional Liability. While redistributing
185
+ the Work or Derivative Works thereof, You may choose to offer,
186
+ and charge a fee for, acceptance of support, warranty, indemnity,
187
+ or other liability obligations and/or rights consistent with this
188
+ License. However, in accepting such obligations, You may act only
189
+ on Your own behalf and on Your sole responsibility, not on behalf
190
+ of any other Contributor, and only if You agree to indemnify,
191
+ defend, and hold each Contributor harmless for any liability
192
+ incurred by, or claims asserted against, such Contributor by reason
193
+ of your accepting any such warranty or additional liability.
194
+
195
+ END OF TERMS AND CONDITIONS
196
+
197
+ APPENDIX: How to apply the Apache License to your work.
198
+
199
+ To apply the Apache License to your work, attach the following
200
+ boilerplate notice, with the fields enclosed by brackets "[]"
201
+ replaced with your own identifying information. (Don't include
202
+ the brackets!) The text should be enclosed in the appropriate
203
+ comment syntax for the file format. We also recommend that a
204
+ file or class name and description of purpose be included on the
205
+ same "printed page" as the copyright notice for easier
206
+ identification within third-party archives.
207
+
208
+ Copyright [yyyy] [name of copyright owner]
209
+
210
+ Licensed under the Apache License, Version 2.0 (the "License");
211
+ you may not use this file except in compliance with the License.
212
+ You may obtain a copy of the License at
213
+
214
+ http://www.apache.org/licenses/LICENSE-2.0
215
+
216
+ Unless required by applicable law or agreed to in writing, software
217
+ distributed under the License is distributed on an "AS IS" BASIS,
218
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
219
+ See the License for the specific language governing permissions and
220
+ limitations under the License.