clearspark 0.0.1__tar.gz

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,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vinicius de Oliveira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: clearspark
3
+ Version: 0.0.1
4
+ Summary: A curated collection of essential PySpark functions for daily data engineering.
5
+ Project-URL: Repository, https://github.com/v-skolder/clearspark
6
+ Project-URL: owner, https://github.com/v-skolder
7
+ Author-email: Vinicius <vinnyuniverso3@gmail.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: bucketing,categorization,data-engineering,dataframe,etl,pyspark,spark-utils
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.8
24
+ Requires-Dist: pydantic>=2.0
25
+ Requires-Dist: pyspark>=3.5.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest; extra == 'dev'
28
+ Requires-Dist: pytest-cov; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ <img src="docs/assets/images/readme-logo.png"/>
32
+
33
+ # clearspark
34
+
35
+ **clearspark** is a lightweight PySpark utility library that makes common data transformation patterns cleaner, faster to write, and easier to read. Stop rewriting the same boilerplate `when/otherwise` chains — clearspark gives you expressive, validated, one-liner functions.
36
+
37
+ **[Function reference →](docs/functions.md)**
38
+
39
+ ---
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install git+https://github.com/v-skolder/clearspark.git
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Importing
50
+
51
+ ```python
52
+ import clearspark.functions as cf
53
+ ```
@@ -0,0 +1,23 @@
1
+ <img src="docs/assets/images/readme-logo.png"/>
2
+
3
+ # clearspark
4
+
5
+ **clearspark** is a lightweight PySpark utility library that makes common data transformation patterns cleaner, faster to write, and easier to read. Stop rewriting the same boilerplate `when/otherwise` chains — clearspark gives you expressive, validated, one-liner functions.
6
+
7
+ **[Function reference →](docs/functions.md)**
8
+
9
+ ---
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install git+https://github.com/v-skolder/clearspark.git
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Importing
20
+
21
+ ```python
22
+ import clearspark.functions as cf
23
+ ```
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "clearspark"
7
+ version = "0.0.1"
8
+ description = "A curated collection of essential PySpark functions for daily data engineering."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+ keywords = ["pyspark", "data-engineering", "dataframe", "etl", "spark-utils", "bucketing", "categorization"]
13
+ authors = [
14
+ {name = "Vinicius", email = "vinnyuniverso3@gmail.com"},
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Science/Research",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Topic :: Scientific/Engineering :: Information Analysis",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.8",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: OS Independent",
29
+ ]
30
+ dependencies = [
31
+ "pyspark>=3.5.0",
32
+ "pydantic>=2.0"
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ dev = [
37
+ "pytest",
38
+ "pytest-cov",
39
+ ]
40
+
41
+ [project.urls]
42
+ Repository = "https://github.com/v-skolder/clearspark"
43
+ owner = "https://github.com/v-skolder"
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["/src"]
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/clearspark"]
50
+
51
+ [tool.mypy]
52
+ python_version = "3.8"
53
+ warn_return_any = true
54
+ warn_unused_configs = true
55
+ disallow_untyped_defs = true
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+
2
+ __all__ = [
3
+ 'functions'
4
+ ]
@@ -0,0 +1,48 @@
1
+
2
+ from typing import (
3
+ Annotated,
4
+ Any,
5
+ Optional
6
+ )
7
+
8
+ from pydantic import BeforeValidator
9
+
10
+ __all__ = ["DuckSparkSession", "DuckSparkDataFrame", "DuckSparkColumn"]
11
+
12
+ # UTILS
13
+
14
+ def _hasattrs(v: Any, required_attr: list[str]) -> bool:
15
+ return all(hasattr(v, attr) for attr in required_attr)
16
+
17
+
18
+ # VALIDATE FUNCTIONS
19
+
20
+ def validate_spark_session(v: Any) -> Any:
21
+ required_attr = ["read", "createDataFrame", "table", "catalog"]
22
+
23
+ if not _hasattrs(v, required_attr) and v is not None:
24
+ raise ValueError(f"Invalid SparkSession-like object: {type(v).__name__}")
25
+
26
+ return v
27
+
28
+
29
+ def validate_spark_dataframe(v: Any) -> Any:
30
+ required_attr = ["select", "columns", "filter", "groupBy", "withColumn"]
31
+
32
+ if not _hasattrs(v, required_attr):
33
+ raise ValueError(f"Invalid Dataframe-like object: {type(v).__name__}")
34
+
35
+
36
+ def validate_spark_column(v: Any) -> Any:
37
+ required_attr = ["alias", "cast", "desc", "asc"]
38
+
39
+ if not _hasattrs(v, required_attr):
40
+ raise ValueError(f"Invalid Column-like object: {type(v).__name__}")
41
+
42
+ # ANNOTATIONS
43
+
44
+ DuckSparkSession = Optional[Annotated[Any, BeforeValidator(validate_spark_session)]]
45
+
46
+ DuckSparkDataFrame = Annotated[Any, BeforeValidator(validate_spark_dataframe)]
47
+
48
+ DuckSparkColumn = Annotated[Any, BeforeValidator(validate_spark_column)]
@@ -0,0 +1,129 @@
1
+
2
+ from clearspark.annotations import (
3
+ DuckSparkColumn,
4
+ DuckSparkSession,
5
+ DuckSparkDataFrame
6
+ )
7
+
8
+ from typing import (
9
+ Optional,
10
+ Union
11
+ )
12
+
13
+ from pydantic import (
14
+ ConfigDict,
15
+ validate_call
16
+ )
17
+
18
+ from pyspark.sql import (
19
+ DataFrame,
20
+ SparkSession
21
+ )
22
+
23
+ __all__ = [
24
+ "load_data",
25
+ "save_data"
26
+ ]
27
+
28
+ # UTILS
29
+
30
+ def _is_catalog_path(path: str):
31
+ return '/' not in path
32
+
33
+ # FUNCTIONS
34
+
35
+ @validate_call(config=ConfigDict(arbitrary_types_allowed=True))
36
+ def load_data(
37
+ path: str,
38
+ format: str = "delta",
39
+ select_cols: Optional[Union[list[str], list[DuckSparkColumn]]] = None,
40
+ filter_spec: Optional[Union[str, DuckSparkColumn]] = None,
41
+ spark_session: Optional[DuckSparkSession] = None,
42
+ ) -> DataFrame:
43
+ """Loads a DataFrame from a catalog table or file path.
44
+
45
+ Reads data using the given format, optionally selecting specific
46
+ columns and applying a filter. The source is resolved as a catalog
47
+ table if `path` contains no "/", otherwise as a file path.
48
+
49
+ Args:
50
+ path: Catalog table name (e.g. "db.table") or file path
51
+ (e.g. "/data/events").
52
+ format: Data source format. Defaults to "delta".
53
+ select_cols: Columns to select, as column names or
54
+ `DuckSparkColumn` expressions. If None, all columns are
55
+ returned.
56
+ filter_spec: Filter condition as a SQL string or a
57
+ `DuckSparkColumn` expression. If None, no filter is applied.
58
+ spark_session: Session to use. If None, the active
59
+ `SparkSession` is used.
60
+
61
+ Returns:
62
+ A `DataFrame` with the loaded (and optionally filtered/selected)
63
+ data.
64
+
65
+ Raises:
66
+ ValueError: If no active Spark session is found and
67
+ `spark_session` is not provided.
68
+
69
+ Example:
70
+ >>> load_data("db.events", select_cols=["id", "ts"])
71
+ >>> load_data("/data/events", format="parquet", filter_spec="ts > 0")
72
+ """
73
+
74
+ reader = (spark_session or SparkSession.getActiveSession()).read.format(format)
75
+
76
+ df = reader.table(path) if _is_catalog_path else reader.load(path)
77
+
78
+ if select_cols is not None:
79
+ df = df.select(select_cols)
80
+
81
+ if filter_spec is not None:
82
+ df = df.filter(filter_spec)
83
+
84
+ return df
85
+
86
+ @validate_call(config=ConfigDict(arbitrary_types_allowed=True))
87
+ def save_data(
88
+ df: DuckSparkDataFrame,
89
+ data_path: str,
90
+ data_format: str = 'delta',
91
+ mode: str = 'overwrite',
92
+ options: Optional[dict[str, str]] = None,
93
+ partition_by: Optional[list[str]] = None,
94
+ ) -> None:
95
+ """Saves a DataFrame to a catalog table or file path.
96
+
97
+ Args:
98
+ df: The PySpark DataFrame to save.
99
+ data_path: The destination path. If it contains no '/', saves as a catalog table; otherwise, as a file path.
100
+ data_format: The format to save in (e.g., 'delta', 'parquet'). Defaults to 'delta'.
101
+ mode: The save mode ('overwrite', 'append', 'ignore', 'error'). Defaults to 'overwrite'.
102
+ options: Optional dictionary of additional options for the writer.
103
+ partition_by: Optional list of column names to partition by.
104
+
105
+ Returns:
106
+ None
107
+
108
+ Raises:
109
+ ValueError: If the DataFrame or save mode is invalid.
110
+
111
+ Example:
112
+ >>> save_data(df, "db.events")
113
+ >>> save_data(df, "/data/events", data_format="parquet", mode="append")
114
+ >>> save_data(df, "db.events", partition_by=["year", "month"])
115
+ """
116
+ writer = df.write.format(data_format).mode(mode)
117
+
118
+ if options:
119
+ writer = writer.options(**options)
120
+
121
+ if partition_by:
122
+ writer = writer.partitionBy(*partition_by)
123
+
124
+ if _is_catalog_path(data_path):
125
+ writer.saveAsTable(data_path)
126
+ else:
127
+ writer.save(data_path)
128
+
129
+ print(f"Data saved successfully to '{data_path}' in '{data_format}' format with mode '{mode}'.")