typedspark 0.0.0__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.
Files changed (38) hide show
  1. typedspark-0.0.0/LICENSE.txt +201 -0
  2. typedspark-0.0.0/PKG-INFO +93 -0
  3. typedspark-0.0.0/README.md +75 -0
  4. typedspark-0.0.0/pyproject.toml +41 -0
  5. typedspark-0.0.0/setup.cfg +4 -0
  6. typedspark-0.0.0/setup.py +34 -0
  7. typedspark-0.0.0/typedspark/__init__.py +54 -0
  8. typedspark-0.0.0/typedspark/_core/__init__.py +0 -0
  9. typedspark-0.0.0/typedspark/_core/column.py +97 -0
  10. typedspark-0.0.0/typedspark/_core/column_meta.py +26 -0
  11. typedspark-0.0.0/typedspark/_core/dataset.py +302 -0
  12. typedspark-0.0.0/typedspark/_core/datatypes.py +106 -0
  13. typedspark-0.0.0/typedspark/_core/literaltype.py +41 -0
  14. typedspark-0.0.0/typedspark/_core/validate_schema.py +120 -0
  15. typedspark-0.0.0/typedspark/_schema/__init__.py +0 -0
  16. typedspark-0.0.0/typedspark/_schema/dlt_kwargs.py +20 -0
  17. typedspark-0.0.0/typedspark/_schema/get_schema_definition.py +160 -0
  18. typedspark-0.0.0/typedspark/_schema/get_schema_imports.py +146 -0
  19. typedspark-0.0.0/typedspark/_schema/schema.py +208 -0
  20. typedspark-0.0.0/typedspark/_schema/structfield.py +155 -0
  21. typedspark-0.0.0/typedspark/_transforms/__init__.py +0 -0
  22. typedspark-0.0.0/typedspark/_transforms/rename_duplicate_columns.py +122 -0
  23. typedspark-0.0.0/typedspark/_transforms/structtype_column.py +56 -0
  24. typedspark-0.0.0/typedspark/_transforms/transform_to_schema.py +74 -0
  25. typedspark-0.0.0/typedspark/_transforms/utils.py +46 -0
  26. typedspark-0.0.0/typedspark/_utils/__init__.py +0 -0
  27. typedspark-0.0.0/typedspark/_utils/camelcase.py +6 -0
  28. typedspark-0.0.0/typedspark/_utils/create_dataset.py +131 -0
  29. typedspark-0.0.0/typedspark/_utils/create_dataset_from_structtype.py +71 -0
  30. typedspark-0.0.0/typedspark/_utils/databases.py +229 -0
  31. typedspark-0.0.0/typedspark/_utils/load_table.py +90 -0
  32. typedspark-0.0.0/typedspark/_utils/register_schema_to_dataset.py +95 -0
  33. typedspark-0.0.0/typedspark/py.typed +0 -0
  34. typedspark-0.0.0/typedspark.egg-info/PKG-INFO +93 -0
  35. typedspark-0.0.0/typedspark.egg-info/SOURCES.txt +36 -0
  36. typedspark-0.0.0/typedspark.egg-info/dependency_links.txt +1 -0
  37. typedspark-0.0.0/typedspark.egg-info/requires.txt +4 -0
  38. typedspark-0.0.0/typedspark.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.1
2
+ Name: typedspark
3
+ Version: 0.0.0
4
+ Summary: Column-wise type annotations for pyspark DataFrames
5
+ Home-page: https://github.com/kaiko-ai/typedspark
6
+ Author: Nanne Aben
7
+ Author-email: nanne@kaiko.ai
8
+ License: Apache-2.0
9
+ Keywords: pyspark spark typing type checking annotations
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.9.0
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE.txt
15
+ Requires-Dist: typing-extensions<=4.11.0
16
+ Provides-Extra: pyspark
17
+ Requires-Dist: pyspark; extra == "pyspark"
18
+
19
+ # Typedspark: column-wise type annotations for pyspark DataFrames
20
+
21
+ We love Spark! But in production code we're wary when we see:
22
+
23
+ ```python
24
+ from pyspark.sql import DataFrame
25
+
26
+ def foo(df: DataFrame) -> DataFrame:
27
+ # do stuff
28
+ return df
29
+ ```
30
+
31
+ Because… How do we know which columns are supposed to be in ``df``?
32
+
33
+ Using ``typedspark``, we can be more explicit about what these data should look like.
34
+
35
+ ```python
36
+ from typedspark import Column, DataSet, Schema
37
+ from pyspark.sql.types import LongType, StringType
38
+
39
+ class Person(Schema):
40
+ id: Column[LongType]
41
+ name: Column[StringType]
42
+ age: Column[LongType]
43
+
44
+ def foo(df: DataSet[Person]) -> DataSet[Person]:
45
+ # do stuff
46
+ return df
47
+ ```
48
+ The advantages include:
49
+
50
+ * Improved readibility of the code
51
+ * Typechecking, both during runtime and linting
52
+ * Auto-complete of column names
53
+ * Easy refactoring of column names
54
+ * Easier unit testing through the generation of empty ``DataSets`` based on their schemas
55
+ * Improved documentation of tables
56
+
57
+ ## Documentation
58
+ Please see our documentation on [readthedocs](https://typedspark.readthedocs.io/en/latest/index.html).
59
+
60
+ ## Installation
61
+
62
+ You can install ``typedspark`` from [pypi](https://pypi.org/project/typedspark/) by running:
63
+
64
+ ```bash
65
+ pip install typedspark
66
+ ```
67
+ By default, ``typedspark`` does not list ``pyspark`` as a dependency, since many platforms (e.g. Databricks) come with ``pyspark`` preinstalled. If you want to install ``typedspark`` with ``pyspark``, you can run:
68
+
69
+ ```bash
70
+ pip install "typedspark[pyspark]"
71
+ ```
72
+
73
+ ## Demo videos
74
+
75
+ ### IDE demo
76
+
77
+ https://github.com/kaiko-ai/typedspark/assets/47976799/e6f7fa9c-6d14-4f68-baba-fe3c22f75b67
78
+
79
+ You can find the corresponding code [here](docs/videos/ide.ipynb).
80
+
81
+ ### Jupyter / Databricks notebooks demo
82
+
83
+ https://github.com/kaiko-ai/typedspark/assets/47976799/39e157c3-6db0-436a-9e72-44b2062df808
84
+
85
+ You can find the corresponding code [here](docs/videos/notebook.ipynb).
86
+
87
+ ## FAQ
88
+
89
+ **I found a bug! What should I do?**</br>
90
+ Great! Please make an issue and we'll look into it.
91
+
92
+ **I have a great idea to improve typedspark! How can we make this work?**</br>
93
+ Awesome, please make an issue and let us know!
@@ -0,0 +1,75 @@
1
+ # Typedspark: column-wise type annotations for pyspark DataFrames
2
+
3
+ We love Spark! But in production code we're wary when we see:
4
+
5
+ ```python
6
+ from pyspark.sql import DataFrame
7
+
8
+ def foo(df: DataFrame) -> DataFrame:
9
+ # do stuff
10
+ return df
11
+ ```
12
+
13
+ Because… How do we know which columns are supposed to be in ``df``?
14
+
15
+ Using ``typedspark``, we can be more explicit about what these data should look like.
16
+
17
+ ```python
18
+ from typedspark import Column, DataSet, Schema
19
+ from pyspark.sql.types import LongType, StringType
20
+
21
+ class Person(Schema):
22
+ id: Column[LongType]
23
+ name: Column[StringType]
24
+ age: Column[LongType]
25
+
26
+ def foo(df: DataSet[Person]) -> DataSet[Person]:
27
+ # do stuff
28
+ return df
29
+ ```
30
+ The advantages include:
31
+
32
+ * Improved readibility of the code
33
+ * Typechecking, both during runtime and linting
34
+ * Auto-complete of column names
35
+ * Easy refactoring of column names
36
+ * Easier unit testing through the generation of empty ``DataSets`` based on their schemas
37
+ * Improved documentation of tables
38
+
39
+ ## Documentation
40
+ Please see our documentation on [readthedocs](https://typedspark.readthedocs.io/en/latest/index.html).
41
+
42
+ ## Installation
43
+
44
+ You can install ``typedspark`` from [pypi](https://pypi.org/project/typedspark/) by running:
45
+
46
+ ```bash
47
+ pip install typedspark
48
+ ```
49
+ By default, ``typedspark`` does not list ``pyspark`` as a dependency, since many platforms (e.g. Databricks) come with ``pyspark`` preinstalled. If you want to install ``typedspark`` with ``pyspark``, you can run:
50
+
51
+ ```bash
52
+ pip install "typedspark[pyspark]"
53
+ ```
54
+
55
+ ## Demo videos
56
+
57
+ ### IDE demo
58
+
59
+ https://github.com/kaiko-ai/typedspark/assets/47976799/e6f7fa9c-6d14-4f68-baba-fe3c22f75b67
60
+
61
+ You can find the corresponding code [here](docs/videos/ide.ipynb).
62
+
63
+ ### Jupyter / Databricks notebooks demo
64
+
65
+ https://github.com/kaiko-ai/typedspark/assets/47976799/39e157c3-6db0-436a-9e72-44b2062df808
66
+
67
+ You can find the corresponding code [here](docs/videos/notebook.ipynb).
68
+
69
+ ## FAQ
70
+
71
+ **I found a bug! What should I do?**</br>
72
+ Great! Please make an issue and we'll look into it.
73
+
74
+ **I have a great idea to improve typedspark! How can we make this work?**</br>
75
+ Awesome, please make an issue and let us know!
@@ -0,0 +1,41 @@
1
+ [tool.black]
2
+ line-length = 100
3
+
4
+ [tool.isort]
5
+ profile = "black"
6
+ line_length = 100
7
+
8
+ [tool.pylint]
9
+ ignore-paths = ['^tests/.+.py$', 'setup.py', '^docs/.+.py$']
10
+
11
+ [tool.pylint."messages control"]
12
+ disable = "all"
13
+ enable = [
14
+ "empty-docstring",
15
+ "missing-module-docstring",
16
+ "missing-class-docstring",
17
+ "missing-function-docstring",
18
+ "unidiomatic-typecheck",
19
+ "no-else-return",
20
+ "consider-using-dict-comprehension",
21
+ "dangerous-default-value",
22
+ "unspecified-encoding",
23
+ "unnecessary-pass",
24
+ "redefined-outer-name",
25
+ "invalid-name",
26
+ "unused-argument",
27
+ "redefined-builtin",
28
+ "simplifiable-if-expression",
29
+ "logging-fstring-interpolation",
30
+ "inconsistent-return-statements",
31
+ "consider-using-set-comprehension"
32
+ ]
33
+
34
+ [tool.coverage.run]
35
+ source = ["typedspark/"]
36
+
37
+ [tool.mypy]
38
+ exclude = ['^docs\/.+\.py$']
39
+
40
+ [tool.bandit]
41
+ exclude_dirs = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ from setuptools import find_packages, setup
2
+
3
+
4
+ def get_requirements():
5
+ with open("requirements.txt") as f:
6
+ return f.read().splitlines()
7
+
8
+
9
+ def get_long_description():
10
+ with open("README.md", encoding="utf-8") as f:
11
+ return f.read()
12
+
13
+
14
+ setup(
15
+ name="typedspark",
16
+ url="https://github.com/kaiko-ai/typedspark",
17
+ license="Apache-2.0",
18
+ author="Nanne Aben",
19
+ author_email="nanne@kaiko.ai",
20
+ description="Column-wise type annotations for pyspark DataFrames",
21
+ keywords="pyspark spark typing type checking annotations",
22
+ long_description=get_long_description(),
23
+ long_description_content_type="text/markdown",
24
+ packages=find_packages(include=["typedspark", "typedspark.*"]),
25
+ install_requires=get_requirements(),
26
+ python_requires=">=3.9.0",
27
+ classifiers=["Programming Language :: Python", "Typing :: Typed"],
28
+ version_config=True,
29
+ setup_requires=["setuptools-git-versioning"],
30
+ package_data={"typedspark": ["py.typed"]},
31
+ extras_require={
32
+ "pyspark": ["pyspark"],
33
+ },
34
+ )
@@ -0,0 +1,54 @@
1
+ """Typedspark: column-wise type annotations for pyspark DataFrames."""
2
+
3
+ from typedspark._core.column import Column
4
+ from typedspark._core.column_meta import ColumnMeta
5
+ from typedspark._core.dataset import DataSet, DataSetImplements
6
+ from typedspark._core.datatypes import (
7
+ ArrayType,
8
+ DayTimeIntervalType,
9
+ DecimalType,
10
+ MapType,
11
+ StructType,
12
+ )
13
+ from typedspark._core.literaltype import IntervalType
14
+ from typedspark._schema.schema import MetaSchema, Schema
15
+ from typedspark._transforms.structtype_column import structtype_column
16
+ from typedspark._transforms.transform_to_schema import transform_to_schema
17
+ from typedspark._utils.create_dataset import (
18
+ create_empty_dataset,
19
+ create_partially_filled_dataset,
20
+ create_structtype_row,
21
+ )
22
+ from typedspark._utils.databases import Catalogs, Database, Databases
23
+ from typedspark._utils.load_table import create_schema, load_table
24
+ from typedspark._utils.register_schema_to_dataset import (
25
+ register_schema_to_dataset,
26
+ register_schema_to_dataset_with_alias,
27
+ )
28
+
29
+ __all__ = [
30
+ "ArrayType",
31
+ "Catalogs",
32
+ "Column",
33
+ "ColumnMeta",
34
+ "Database",
35
+ "Databases",
36
+ "DataSet",
37
+ "DayTimeIntervalType",
38
+ "DecimalType",
39
+ "IntervalType",
40
+ "MapType",
41
+ "MetaSchema",
42
+ "DataSetImplements",
43
+ "Schema",
44
+ "StructType",
45
+ "create_empty_dataset",
46
+ "create_partially_filled_dataset",
47
+ "create_structtype_row",
48
+ "create_schema",
49
+ "load_table",
50
+ "register_schema_to_dataset",
51
+ "register_schema_to_dataset_with_alias",
52
+ "structtype_column",
53
+ "transform_to_schema",
54
+ ]
File without changes
@@ -0,0 +1,97 @@
1
+ """Module containing classes and functions related to TypedSpark Columns."""
2
+
3
+ from logging import warn
4
+ from typing import Generic, Optional, TypeVar, Union, get_args, get_origin
5
+
6
+ from pyspark.sql import Column as SparkColumn
7
+ from pyspark.sql import DataFrame, SparkSession
8
+ from pyspark.sql.functions import col
9
+ from pyspark.sql.types import DataType
10
+
11
+ from typedspark._core.datatypes import StructType
12
+
13
+ T = TypeVar("T", bound=DataType)
14
+
15
+
16
+ class EmptyColumn(SparkColumn):
17
+ """Column object to be instantiated when there is no active Spark session."""
18
+
19
+ def __init__(self, *args, **kwargs) -> None: # pragma: no cover
20
+ pass
21
+
22
+
23
+ class Column(SparkColumn, Generic[T]):
24
+ """Represents a ``Column`` in a ``Schema``. Can be used as:
25
+
26
+ .. code-block:: python
27
+
28
+ class A(Schema):
29
+ a: Column[IntegerType]
30
+ b: Column[StringType]
31
+ """
32
+
33
+ def __new__(
34
+ cls,
35
+ name: str,
36
+ dataframe: Optional[DataFrame] = None,
37
+ curid: Optional[int] = None,
38
+ dtype: Optional[T] = None,
39
+ parent: Union[DataFrame, "Column", None] = None,
40
+ alias: Optional[str] = None,
41
+ ):
42
+ """``__new__()`` instantiates the object (prior to ``__init__()``).
43
+
44
+ Here, we simply take the provided ``name``, create a pyspark
45
+ ``Column`` object and cast it to a typedspark ``Column`` object.
46
+ This allows us to bypass the pypsark ``Column`` constuctor in
47
+ ``__init__()``, which requires parameters that may be difficult
48
+ to access.
49
+ """
50
+ # pylint: disable=unused-argument
51
+
52
+ if dataframe is not None and parent is None:
53
+ parent = dataframe
54
+ warn("The use of Column(dataframe=...) is deprecated, use Column(parent=...) instead.")
55
+
56
+ column: SparkColumn
57
+ if SparkSession.getActiveSession() is None:
58
+ column = EmptyColumn() # pragma: no cover
59
+ elif alias is not None:
60
+ column = col(f"{alias}.{name}")
61
+ elif parent is not None:
62
+ column = parent[name]
63
+ else:
64
+ column = col(name)
65
+
66
+ column.__class__ = Column
67
+ return column
68
+
69
+ def __init__(
70
+ self,
71
+ name: str,
72
+ dataframe: Optional[DataFrame] = None,
73
+ curid: Optional[int] = None,
74
+ dtype: Optional[T] = None,
75
+ parent: Union[DataFrame, "Column", None] = None,
76
+ alias: Optional[str] = None,
77
+ ):
78
+ # pylint: disable=unused-argument
79
+ self.str = name
80
+ self._dtype = dtype if dtype is not None else DataType
81
+ self._curid = curid
82
+
83
+ def __hash__(self) -> int:
84
+ return hash((self.str, self._curid))
85
+
86
+ @property
87
+ def dtype(self) -> T:
88
+ """Get the datatype of the column, e.g. Column[IntegerType] -> IntegerType."""
89
+ dtype = self._dtype
90
+
91
+ if get_origin(dtype) == StructType:
92
+ return StructType(
93
+ schema=get_args(dtype)[0],
94
+ parent=self,
95
+ ) # type: ignore
96
+
97
+ return dtype() # type: ignore
@@ -0,0 +1,26 @@
1
+ """Metadata for ``Column`` objects that can be accessed during runtime."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Optional
5
+
6
+
7
+ @dataclass
8
+ class ColumnMeta:
9
+ """Contains the metadata for a ``Column``. Used as:
10
+
11
+ .. code-block:: python
12
+
13
+ class A(Schema):
14
+ a: Annotated[
15
+ Column[IntegerType],
16
+ ColumnMeta(
17
+ comment="This is a comment",
18
+ )
19
+ ]
20
+ """
21
+
22
+ comment: Optional[str] = None
23
+
24
+ def get_metadata(self) -> Optional[Dict[str, str]]:
25
+ """Returns the metadata of this column."""
26
+ return {"comment": self.comment} if self.comment else None