Skip to content

Checks

toolbox_pyspark.checks 🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

Column Existence🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

ColumnExistsResult dataclass 🔗

Source code in src/toolbox_pyspark/checks.py
109
110
111
112
113
114
115
116
@dataclass
class ColumnExistsResult:
    result: bool
    missing_cols: str_list

    def __iter__(self):
        for field in fields(self):
            yield getattr(self, field.name)

__init__ 🔗

__init__(result: bool, missing_cols: str_list) -> None

result instance-attribute 🔗

result: bool

missing_cols instance-attribute 🔗

missing_cols: str_list

__iter__ 🔗

__iter__()
Source code in src/toolbox_pyspark/checks.py
114
115
116
def __iter__(self):
    for field in fields(self):
        yield getattr(self, field.name)

column_exists 🔗

column_exists(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> bool

Summary

Check whether a given column exists as a valid column within dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
match_case bool

Whether or not to match the string case for the columns.
If False, will default to: column.upper().
Default: False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

True if exists or False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import column_exists
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example1: Column Exists
1
2
>>> result = column_exists(df, "a")
>>> print(result)
Terminal
True

Conclusion: Column exists.

Example 2: Column Missing
1
2
>>> result = column_exists(df, "c")
>>> print(result)
Terminal
False

Conclusion: Column does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
@typechecked
def column_exists(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> bool:
    """
    !!! note "Summary"
        Check whether a given `#!py column` exists as a valid column within `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            If `#!py False`, will default to: `#!py column.upper()`.<br>
            Default: `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            `#!py True` if exists or `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import column_exists
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example1: Column Exists"}
        >>> result = column_exists(df, "a")
        >>> print(result)
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Column exists."
        </div>

        ```{.py .python linenums="1" title="Example 2: Column Missing"}
        >>> result = column_exists(df, "c")
        >>> print(result)
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    return _columns_exists(dataframe, [column], match_case).result

columns_exists 🔗

columns_exists(
    dataframe: psDataFrame,
    columns: str_collection,
    match_case: bool = False,
) -> bool

Summary

Check whether all of the values in columns exist in dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str_list, str_tuple, str_set]

The columns to check.

required
match_case bool

Whether or not to match the string case for the columns.
If False, will default to: [col.upper() for col in columns].
Default: False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

True if all columns exist or False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import columns_exists
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: Columns exist
1
>>> columns_exists(df, ["a", "b"])
Terminal
True

Conclusion: All columns exist.

Example 2: One column missing
1
>>> columns_exists(df, ["b", "d"])
Terminal
False

Conclusion: One column is missing.

Example 3: All columns missing
1
>>> columns_exists(df, ["c", "d"])
Terminal
False

Conclusion: All columns are missing.

See Also
Source code in src/toolbox_pyspark/checks.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
@typechecked
def columns_exists(
    dataframe: psDataFrame,
    columns: str_collection,
    match_case: bool = False,
) -> bool:
    """
    !!! note "Summary"
        Check whether all of the values in `#!py columns` exist in `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str_list, str_tuple, str_set]):
            The columns to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            If `#!py False`, will default to: `#!py [col.upper() for col in columns]`.<br>
            Default: `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            `#!py True` if all columns exist or `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import columns_exists
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: Columns exist"}
        >>> columns_exists(df, ["a", "b"])
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: All columns exist."
        </div>

        ```{.py .python linenums="1" title="Example 2: One column missing"}
        >>> columns_exists(df, ["b", "d"])
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: One column is missing."
        </div>

        ```{.py .python linenums="1" title="Example 3: All columns missing"}
        >>> columns_exists(df, ["c", "d"])
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: All columns are missing."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    return _columns_exists(dataframe, columns, match_case).result

assert_column_exists 🔗

assert_column_exists(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> None

Summary

Check whether a given column exists as a valid column within dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
match_case bool

Whether or not to match the string case for the columns.
If False, will default to: column.upper().
Default: True.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If the column does not exist within dataframe.columns.

Returns:

Type Description
type(None)

Nothing is returned. Either an ColumnDoesNotExistError exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import assert_column_exists
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1,2,3,4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No error
1
>>> assert_column_exists(df, "a")
Terminal
None

Conclusion: Column exists.

Example 2: Error raised
1
>>> assert_column_exists(df, "c")
Terminal
ColumnDoesNotExistError: Column "c" does not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Column does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
@typechecked
def assert_column_exists(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether a given `#!py column` exists as a valid column within `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            If `#!py False`, will default to: `#!py column.upper()`.<br>
            Default: `#!py True`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If the `#!py column` does not exist within `#!py dataframe.columns`.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py ColumnDoesNotExistError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import assert_column_exists
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1,2,3,4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> assert_column_exists(df, "a")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Column exists."
        </div>

        ```{.py .python linenums="1" title="Example 2: Error raised"}
        >>> assert_column_exists(df, "c")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Column "c" does not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    if not column_exists(dataframe, column, match_case):
        raise ColumnDoesNotExistError(
            f"Column '{column}' does not exist in 'dataframe'.\n"
            f"Try one of: {dataframe.columns}."
        )

assert_columns_exists 🔗

assert_columns_exists(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    match_case: bool = False,
) -> None

Summary

Check whether all of the values in columns exist in dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str_list, str_tuple, str_set]

The columns to check.

required
match_case bool

Whether or not to match the string case for the columns.
If False, will default to: [col.upper() for col in columns].
Default: True.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If any of the columns do not exist within dataframe.columns.

Returns:

Type Description
type(None)

Nothing is returned. Either an ColumnDoesNotExistError exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import assert_columns_exists
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No error
1
>>> assert_columns_exists(df, ["a", "b"])
Terminal
None

Conclusion: Columns exist.

Example 2: One column missing
1
>>> assert_columns_exists(df, ["b", "c"])
Terminal
ColumnDoesNotExistError: Columns ["c"] do not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Column "c" does not exist.

Example 3: Multiple columns missing
1
>>> assert_columns_exists(df, ["b", "c", "d"])
Terminal
ColumnDoesNotExistError: Columns ["c", "d"] do not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Columns "c" and "d" does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
@typechecked
def assert_columns_exists(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether all of the values in `#!py columns` exist in `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str_list, str_tuple, str_set]):
            The columns to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            If `#!py False`, will default to: `#!py [col.upper() for col in columns]`.<br>
            Default: `#!py True`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If any of the `#!py columns` do not exist within `#!py dataframe.columns`.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py ColumnDoesNotExistError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import assert_columns_exists
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> assert_columns_exists(df, ["a", "b"])
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Columns exist."
        </div>

        ```{.py .python linenums="1" title="Example 2: One column missing"}
        >>> assert_columns_exists(df, ["b", "c"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Columns ["c"] do not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Column "c" does not exist."
        </div>

        ```{.py .python linenums="1" title="Example 3: Multiple columns missing"}
        >>> assert_columns_exists(df, ["b", "c", "d"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Columns ["c", "d"] do not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Columns "c" and "d" does not exist."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    columns = [columns] if is_type(columns, str) else columns
    (exist, missing_cols) = _columns_exists(dataframe, columns, match_case)
    if not exist:
        raise ColumnDoesNotExistError(
            f"Columns {missing_cols} do not exist in 'dataframe'.\n"
            f"Try one of: {dataframe.columns}"
        )

warn_column_missing 🔗

warn_column_missing(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> None

Summary

Check whether a given column exists as a valid column within dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
type(None)

Nothing is returned. Either an ColumnDoesNotExistWarning exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import warn_column_missing
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No error
1
>>> warn_column_missing(df, ["a", "b"])
Terminal
None

Conclusion: Columns exist.

Example 2: Warning raised
1
>>> warn_column_missing(df, "c")
Terminal
ColumnDoesNotExistWarning: Column "c" does not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Column does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
@typechecked
def warn_column_missing(
    dataframe: psDataFrame,
    column: str,
    match_case: bool = False,
) -> None:
    """
    !!! summary "Summary"
        Check whether a given `#!py column` exists as a valid column within `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py ColumnDoesNotExistWarning` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import warn_column_missing
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> warn_column_missing(df, ["a", "b"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        None
        ```
        !!! success "Conclusion: Columns exist."
        </div>

        ```{.py .python linenums="1" title="Example 2: Warning raised"}
        >>> warn_column_missing(df, "c")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistWarning: Column "c" does not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    if not column_exists(dataframe, column, match_case):
        warn(
            f"Column '{column}' does not exist in 'dataframe'.\n"
            f"Try one of: {dataframe.columns}.",
            ColumnDoesNotExistWarning,
        )

warn_columns_missing 🔗

warn_columns_missing(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    match_case: bool = False,
) -> None

Summary

Check whether all of the values in columns exist in dataframe.columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str, str_collection]

The columns to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
type(None)

Nothing is returned. Either an ColumnDoesNotExistWarning exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import warn_columns_missing
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No error
1
>>> warn_columns_missing(df, ["a", "b"])
Terminal
None

Conclusion: Columns exist.

Example 2: One column missing
1
>>> warn_columns_missing(df, ["b", "c"])
Terminal
ColumnDoesNotExistWarning: Columns ["c"] do not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Column "c" does not exist.

Example 3: Multiple columns missing
1
>>> warn_columns_missing(df, ["b", "c", "d"])
Terminal
ColumnDoesNotExistWarning: Columns ["c", "d"] do not exist in "dataframe".
Try one of: ["a", "b"].

Conclusion: Columns "c" and "d" does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
@typechecked
def warn_columns_missing(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    match_case: bool = False,
) -> None:
    """
    !!! summary "Summary"
        Check whether all of the values in `#!py columns` exist in `#!py dataframe.columns`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str, str_collection]):
            The columns to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py ColumnDoesNotExistWarning` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import warn_columns_missing
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> warn_columns_missing(df, ["a", "b"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        None
        ```
        !!! success "Conclusion: Columns exist."
        </div>

        ```{.py .python linenums="1" title="Example 2: One column missing"}
        >>> warn_columns_missing(df, ["b", "c"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistWarning: Columns ["c"] do not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Column "c" does not exist."
        </div>

        ```{.py .python linenums="1" title="Example 3: Multiple columns missing"}
        >>> warn_columns_missing(df, ["b", "c", "d"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistWarning: Columns ["c", "d"] do not exist in "dataframe".
        Try one of: ["a", "b"].
        ```
        !!! failure "Conclusion: Columns "c" and "d" does not exist."
        </div>

    ??? tip "See Also"
        - [`column_exists`][toolbox_pyspark.checks.column_exists]
        - [`columns_exists`][toolbox_pyspark.checks.columns_exists]
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
        - [`assert_columns_exists`][toolbox_pyspark.checks.assert_columns_exists]
        - [`warn_column_missing`][toolbox_pyspark.checks.warn_column_missing]
        - [`warn_columns_missing`][toolbox_pyspark.checks.warn_columns_missing]
    """
    columns = [columns] if is_type(columns, str) else columns
    (exist, missing_cols) = _columns_exists(dataframe, columns, match_case)
    if not exist:
        warn(
            f"Columns {missing_cols} do not exist in 'dataframe'.\n"
            f"Try one of: {dataframe.columns}",
            ColumnDoesNotExistWarning,
        )

Column Values🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

column_contains_value 🔗

column_contains_value(
    dataframe: psDataFrame,
    column: str,
    value: str,
    match_case: bool = False,
) -> bool

Summary

Check whether a given column contains a specific value in dataframe.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
value str

The value to check for.

required
match_case bool

Whether or not to match the string case for the value.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If the column does not exist within dataframe.columns.

Returns:

Type Description
bool

True if the column contains the value, False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import column_contains_value
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: Value exists
1
>>> column_contains_value(df, "b", "a")
Terminal
True

Conclusion: Value exists in column.

Example 2: Value does not exist
1
>>> column_contains_value(df, "b", "z")
Terminal
False

Conclusion: Value does not exist in column.

See Also
Source code in src/toolbox_pyspark/checks.py
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
@typechecked
def column_contains_value(
    dataframe: psDataFrame,
    column: str,
    value: str,
    match_case: bool = False,
) -> bool:
    """
    !!! note "Summary"
        Check whether a given `#!py column` contains a specific `#!py value` in `#!py dataframe`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        value (str):
            The value to check for.
        match_case (bool, optional):
            Whether or not to match the string case for the value.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If the `#!py column` does not exist within `#!py dataframe.columns`.

    Returns:
        (bool):
            `#!py True` if the column contains the value, `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import column_contains_value
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: Value exists"}
        >>> column_contains_value(df, "b", "a")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Value exists in column."
        </div>

        ```{.py .python linenums="1" title="Example 2: Value does not exist"}
        >>> column_contains_value(df, "b", "z")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Value does not exist in column."
        </div>

    ??? tip "See Also"
        - [`assert_column_exists`][toolbox_pyspark.checks.assert_column_exists]
    """
    assert_column_exists(dataframe, column, match_case)

    if not match_case:
        value = value.lower()
        dataframe = dataframe.withColumn(column, F.lower(F.col(column)))

    return dataframe.filter(f"{column} = '{value}'").count() > 0

Type Checks🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

is_vaid_spark_type 🔗

is_vaid_spark_type(datatype: str) -> bool

Summary

Check whether a given datatype is a correct and valid pyspark data type.

Parameters:

Name Type Description Default
datatype str

The name of the data type to check.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

InvalidPySparkDataTypeError

If the given datatype is not a valid pyspark data type.

Returns:

Type Description
bool

True if the datatype is valid, False otherwise.

Examples
Set up
1
>>> from toolbox_pyspark.checks import is_vaid_spark_type

Loop through all valid types
1
2
3
>>> type_names = ["string", "char", "varchar", "binary", "boolean", "decimal", "float", "double", "byte", "short", "integer", "long", "date", "timestamp", "timestamp_ntz", "void"]
>>> for type_name in type_names:
...     is_vaid_spark_type(type_name)
Nothing is returned each time. Because they're all valid.

Conclusion: They're all valid.

Check some invalid types
1
2
3
>>> type_names = ["np.ndarray", "pd.DataFrame", "dict"]
>>> for type_name in type_names:
...     is_vaid_spark_type(type_name)
Terminal
InvalidPySparkDataTypeError: DataType 'np.ndarray' is not valid.
Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
Terminal
InvalidPySparkDataTypeError: DataType 'pd.DataFrame' is not valid.
Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
Terminal
InvalidPySparkDataTypeError: DataType 'dict' is not valid.
Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]

Conclusion: All of these types are invalid.

See Also
Source code in src/toolbox_pyspark/checks.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
@typechecked
def is_vaid_spark_type(datatype: str) -> bool:
    """
    !!! note "Summary"
        Check whether a given `#!py datatype` is a correct and valid `#!py pyspark` data type.

    Params:
        datatype (str):
            The name of the data type to check.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        InvalidPySparkDataTypeError:
            If the given `#!py datatype` is not a valid `#!py pyspark` data type.

    Returns:
        (bool):
            `#!py True` if the datatype is valid, `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_pyspark.checks import is_vaid_spark_type
        ```

        ```{.py .python linenums="1" title="Loop through all valid types"}
        >>> type_names = ["string", "char", "varchar", "binary", "boolean", "decimal", "float", "double", "byte", "short", "integer", "long", "date", "timestamp", "timestamp_ntz", "void"]
        >>> for type_name in type_names:
        ...     is_vaid_spark_type(type_name)
        ```
        <div class="result" markdown>
        Nothing is returned each time. Because they're all valid.
        !!! success "Conclusion: They're all valid."
        </div>

        ```{.py .python linenums="1" title="Check some invalid types"}
        >>> type_names = ["np.ndarray", "pd.DataFrame", "dict"]
        >>> for type_name in type_names:
        ...     is_vaid_spark_type(type_name)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: DataType 'np.ndarray' is not valid.
        Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
        ```
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: DataType 'pd.DataFrame' is not valid.
        Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
        ```
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: DataType 'dict' is not valid.
        Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
        ```
        !!! failure "Conclusion: All of these types are invalid."
        </div>

    ??? tip "See Also"
        - [`assert_valid_spark_type`][toolbox_pyspark.checks.assert_valid_spark_type]
    """
    return datatype in VALID_PYSPARK_TYPE_NAMES

assert_valid_spark_type 🔗

assert_valid_spark_type(datatype: str) -> None

Summary

Assert whether a given datatype is a correct and valid pyspark data type.

Parameters:

Name Type Description Default
datatype str

The name of the data type to check.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

InvalidPySparkDataTypeError

If the given datatype is not a valid pyspark data type.

Returns:

Type Description
type(None)

Nothing is returned. Either an InvalidPySparkDataTypeError exception is raised, or nothing.

Examples
Set up
1
>>> from toolbox_pyspark.checks import assert_valid_spark_type

Example 1: Valid type
1
>>> assert_valid_spark_type("string")
Terminal
None

Conclusion: Valid type.

Example 2: Invalid type
1
>>> assert_valid_spark_type("invalid_type")
Terminal
InvalidPySparkDataTypeError: DataType 'invalid_type' is not valid.
Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]

Conclusion: Invalid type.

See Also
Source code in src/toolbox_pyspark/checks.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
@typechecked
def assert_valid_spark_type(datatype: str) -> None:
    """
    !!! note "Summary"
        Assert whether a given `#!py datatype` is a correct and valid `#!py pyspark` data type.

    Params:
        datatype (str):
            The name of the data type to check.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        InvalidPySparkDataTypeError:
            If the given `#!py datatype` is not a valid `#!py pyspark` data type.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py InvalidPySparkDataTypeError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_pyspark.checks import assert_valid_spark_type
        ```

        ```{.py .python linenums="1" title="Example 1: Valid type"}
        >>> assert_valid_spark_type("string")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        None
        ```
        !!! success "Conclusion: Valid type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Invalid type"}
        >>> assert_valid_spark_type("invalid_type")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: DataType 'invalid_type' is not valid.
        Must be one of: ["binary", "bool", "boolean", "byte", "char", "date", "decimal", "double", "float", "int", "integer", "long", "short", "str", "string", "timestamp", "timestamp_ntz", "varchar", "void"]
        ```
        !!! failure "Conclusion: Invalid type."
        </div>

    ??? tip "See Also"
        - [`is_vaid_spark_type`][toolbox_pyspark.checks.is_vaid_spark_type]
    """
    if not is_vaid_spark_type(datatype):
        raise InvalidPySparkDataTypeError(
            f"DataType '{datatype}' is not valid.\n"
            f"Must be one of: {VALID_PYSPARK_TYPE_NAMES}"
        )

Column Types🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

ColumnsAreTypeResult dataclass 🔗

Source code in src/toolbox_pyspark/checks.py
781
782
783
784
785
786
787
788
@dataclass
class ColumnsAreTypeResult:
    result: bool
    invalid_types: list[tuple[str, str]]

    def __iter__(self):
        for field in fields(self):
            yield getattr(self, field.name)

__init__ 🔗

__init__(
    result: bool, invalid_types: list[tuple[str, str]]
) -> None

result instance-attribute 🔗

result: bool

invalid_types instance-attribute 🔗

invalid_types: list[tuple[str, str]]

__iter__ 🔗

__iter__()
Source code in src/toolbox_pyspark/checks.py
786
787
788
def __iter__(self):
    for field in fields(self):
        yield getattr(self, field.name)

column_is_type 🔗

column_is_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> bool

Summary

Check whether a given column is of a given datatype in dataframe.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If the column does not exist within dataframe.columns.

InvalidPySparkDataTypeError

If the datatype is not a valid pyspark data type.

Returns:

Type Description
bool

True if the column is of the given datatype, False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import column_is_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: Column is of type
1
>>> column_is_type(df, "a", "integer")
Terminal
True

Conclusion: Column is the correct type.

Example 2: Column is not of type
1
>>> column_is_type(df, "b", "integer")
Terminal
False

Conclusion: Column is not the correct type.

See Also
Source code in src/toolbox_pyspark/checks.py
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
@typechecked
def column_is_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> bool:
    """
    !!! note "Summary"
        Check whether a given `#!py column` is of a given `#!py datatype` in `#!py dataframe`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If the `#!py column` does not exist within `#!py dataframe.columns`.
        InvalidPySparkDataTypeError:
            If the `#!py datatype` is not a valid `#!py pyspark` data type.

    Returns:
        (bool):
            `#!py True` if the column is of the given `#!py datatype`, `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import column_is_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: Column is of type"}
        >>> column_is_type(df, "a", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Column is the correct type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Column is not of type"}
        >>> column_is_type(df, "b", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Column is not the correct type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid_type]
    """
    return _columns_are_type(dataframe, column, datatype, match_case).result

columns_are_type 🔗

columns_are_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> bool

Summary

Check whether the given columns are of a given datatype in dataframe.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str, str_collection]

The columns to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If any of the columns do not exist within dataframe.columns.

InvalidPySparkDataTypeError

If the datatype is not a valid pyspark data type.

Returns:

Type Description
bool

True if all the columns are of the given datatype, False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import columns_are_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": [1.1, 2.2, 3.3, 4.4],
...         }
...     )
... )

Example 1: Columns are of type
1
>>> columns_are_type(df, ["a", "c"], "double")
Terminal
True

Conclusion: Columns are the correct type.

Example 2: Columns are not of type
1
>>> columns_are_type(df, ["a", "b"], "double")
Terminal
False

Conclusion: Columns are not the correct type.

Example 3: Single column is of type
1
>>> columns_are_type(df, "a", "integer")
Terminal
True

Conclusion: Column is the correct type.

Example 4: Single column is not of type
1
>>> columns_are_type(df, "b", "integer")
Terminal
False

Conclusion: Column is not the correct type.

See Also
Source code in src/toolbox_pyspark/checks.py
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
@typechecked
def columns_are_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> bool:
    """
    !!! note "Summary"
        Check whether the given `#!py columns` are of a given `#!py datatype` in `#!py dataframe`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str, str_collection]):
            The columns to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If any of the `#!py columns` do not exist within `#!py dataframe.columns`.
        InvalidPySparkDataTypeError:
            If the `#!py datatype` is not a valid `#!py pyspark` data type.

    Returns:
        (bool):
            `#!py True` if all the columns are of the given `#!py datatype`, `#!py False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import columns_are_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1.1, 2.2, 3.3, 4.4],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: Columns are of type"}
        >>> columns_are_type(df, ["a", "c"], "double")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Columns are the correct type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Columns are not of type"}
        >>> columns_are_type(df, ["a", "b"], "double")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Columns are not the correct type."
        </div>

        ```{.py .python linenums="1" title="Example 3: Single column is of type"}
        >>> columns_are_type(df, "a", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Column is the correct type."
        </div>

        ```{.py .python linenums="1" title="Example 4: Single column is not of type"}
        >>> columns_are_type(df, "b", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Column is not the correct type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid
    """
    return _columns_are_type(dataframe, columns, datatype, match_case).result

assert_column_is_type 🔗

assert_column_is_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> None

Summary

Check whether a given column is of a given datatype in dataframe.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If the column does not exist within dataframe.columns.

InvalidPySparkDataTypeError

If the given column is not of the given datatype.

Returns:

Type Description
type(None)

Nothing is returned. Either an InvalidPySparkDataTypeError exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import assert_column_is_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No error
1
>>> assert_column_is_type(df, "a", "integer")
Terminal
None

Conclusion: Column is of type.

Example 2: Error raised
1
>>> assert_column_is_type(df, "b", "integer")
Terminal
InvalidPySparkDataTypeError: Column 'b' is not of type 'integer'.

Conclusion: Column is not of type.

See Also
Source code in src/toolbox_pyspark/checks.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
@typechecked
def assert_column_is_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether a given `#!py column` is of a given `#!py datatype` in `#!py dataframe`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If the `#!py column` does not exist within `#!py dataframe.columns`.
        InvalidPySparkDataTypeError:
            If the given `#!py column` is not of the given `#!py datatype`.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py InvalidPySparkDataTypeError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import assert_column_is_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> assert_column_is_type(df, "a", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Column is of type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Error raised"}
        >>> assert_column_is_type(df, "b", "integer")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: Column 'b' is not of type 'integer'.
        ```
        !!! failure "Conclusion: Column is not of type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid
    """
    result, invalid_types = _columns_are_type(dataframe, column, datatype, match_case)
    if not result:
        raise InvalidPySparkDataTypeError(
            f"Column '{column}' is type '{invalid_types[0][1]}', "
            f"which is not the required type: '{datatype}'."
        )

assert_columns_are_type 🔗

assert_columns_are_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> None

Summary

Check whether the given columns are of a given datatype in dataframe.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str, str_collection]

The columns to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If any of the columns do not exist within dataframe.columns.

InvalidPySparkDataTypeError

If any of the given columns are not of the given datatype.

Returns:

Type Description
type(None)

Nothing is returned. Either an InvalidPySparkDataTypeError exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import assert_columns_are_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": [1.1, 2.2, 3.3, 4.4],
...         }
...     )
... )

Example 1: No error
1
>>> assert_columns_are_type(df, ["a", "c"], "double")
Terminal
None

Conclusion: Columns are of type.

Example 2: Error raised
1
>>> assert_columns_are_type(df, ["a", "b"], "double")
Terminal
InvalidPySparkDataTypeError: Columns ['a', 'b'] are types ['int', 'string'], which are not the required type: 'double'.

Conclusion: Columns are not of type.

Example 3: Single column is of type
1
>>> assert_columns_are_type(df, "a", "integer")
Terminal
None

Conclusion: Column is of type.

Example 4: Single column is not of type
1
>>> assert_columns_are_type(df, "b", "integer")
Terminal
InvalidPySparkDataTypeError: Columns ['b'] are types ['string'], which are not the required type: 'integer'.

Conclusion: Column is not of type.

See Also
Source code in src/toolbox_pyspark/checks.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
@typechecked
def assert_columns_are_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether the given `#!py columns` are of a given `#!py datatype` in `#!py dataframe`.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str, str_collection]):
            The columns to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If any of the `#!py columns` do not exist within `#!py dataframe.columns`.
        InvalidPySparkDataTypeError:
            If any of the given `#!py columns` are not of the given `#!py datatype`.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py InvalidPySparkDataTypeError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import assert_columns_are_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1.1, 2.2, 3.3, 4.4],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No error"}
        >>> assert_columns_are_type(df, ["a", "c"], "double")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Columns are of type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Error raised"}
        >>> assert_columns_are_type(df, ["a", "b"], "double")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: Columns ['a', 'b'] are types ['int', 'string'], which are not the required type: 'double'.
        ```
        !!! failure "Conclusion: Columns are not of type."
        </div>

        ```{.py .python linenums="1" title="Example 3: Single column is of type"}
        >>> assert_columns_are_type(df, "a", "integer")
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Column is of type."
        </div>

        ```{.py .python linenums="1" title="Example 4: Single column is not of type"}
        >>> assert_columns_are_type(df, "b", "integer")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeError: Columns ['b'] are types ['string'], which are not the required type: 'integer'.
        ```
        !!! failure "Conclusion: Column is not of type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid
    """
    result, invalid_types = _columns_are_type(dataframe, columns, datatype, match_case)
    if not result:
        raise InvalidPySparkDataTypeError(
            f"Columns {[col for col, _ in invalid_types]} are types {[typ for _, typ in invalid_types]}, "
            f"which are not the required type: '{datatype}'."
        )

warn_column_invalid_type 🔗

warn_column_invalid_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> None

Summary

Check whether a given column is of a given datatype in dataframe and raise a warning if not.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
column str

The column to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
type(None)

Nothing is returned. Either an InvalidPySparkDataTypeWarning exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import warn_column_invalid_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )

Example 1: No warning
1
>>> warn_column_invalid_type(df, "a", "integer")
Terminal
None

Conclusion: Column is of type.

Example 2: Warning raised
1
>>> warn_column_invalid_type(df, "b", "integer")
Terminal
InvalidPySparkDataTypeWarning: Column 'b' is type 'string', which is not the required type: 'integer'.

Conclusion: Column is not of type.

See Also
Source code in src/toolbox_pyspark/checks.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
@typechecked
def warn_column_invalid_type(
    dataframe: psDataFrame,
    column: str,
    datatype: str,
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether a given `#!py column` is of a given `#!py datatype` in `#!py dataframe` and raise a warning if not.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        column (str):
            The column to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py InvalidPySparkDataTypeWarning` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import warn_column_invalid_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No warning"}
        >>> warn_column_invalid_type(df, "a", "integer")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        None
        ```
        !!! success "Conclusion: Column is of type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Warning raised"}
        >>> warn_column_invalid_type(df, "b", "integer")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeWarning: Column 'b' is type 'string', which is not the required type: 'integer'.
        ```
        !!! failure "Conclusion: Column is not of type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid
    """
    result, invalid_types = _columns_are_type(dataframe, column, datatype, match_case)
    if not result:
        warn(
            f"Column '{column}' is type '{invalid_types[0][1]}', "
            f"which is not the required type: '{datatype}'.",
            InvalidPySparkDataTypeWarning,
        )

warn_columns_invalid_type 🔗

warn_columns_invalid_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> None

Summary

Check whether the given columns are of a given datatype in dataframe and raise a warning if not.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to check.

required
columns Union[str, str_collection]

The columns to check.

required
datatype str

The data type to check.

required
match_case bool

Whether or not to match the string case for the columns.
Defaults to False.

False

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
type(None)

Nothing is returned. Either an InvalidPySparkDataTypeWarning exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.checks import warn_columns_invalid_type
>>> spark = SparkSession.builder.getOrCreate()
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": [1.1, 2.2, 3.3, 4.4],
...         }
...     )
... )

Example 1: No warning
1
>>> warn_columns_invalid_type(df, ["a", "c"], "double")
Terminal
None

Conclusion: Columns are of type.

Example 2: Warning raised
1
>>> warn_columns_invalid_type(df, ["a", "b"], "double")
Terminal
InvalidPySparkDataTypeWarning: Columns ['a', 'b'] are types ['int', 'string'], which are not the required type: 'double'.

Conclusion: Columns are not of type.

See Also
Source code in src/toolbox_pyspark/checks.py
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
@typechecked
def warn_columns_invalid_type(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    datatype: str,
    match_case: bool = False,
) -> None:
    """
    !!! note "Summary"
        Check whether the given `#!py columns` are of a given `#!py datatype` in `#!py dataframe` and raise a warning if not.

    Params:
        dataframe (psDataFrame):
            The DataFrame to check.
        columns (Union[str, str_collection]):
            The columns to check.
        datatype (str):
            The data type to check.
        match_case (bool, optional):
            Whether or not to match the string case for the columns.<br>
            Defaults to `#!py False`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py InvalidPySparkDataTypeWarning` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.checks import warn_columns_invalid_type
        >>> spark = SparkSession.builder.getOrCreate()
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1.1, 2.2, 3.3, 4.4],
        ...         }
        ...     )
        ... )
        ```

        ```{.py .python linenums="1" title="Example 1: No warning"}
        >>> warn_columns_invalid_type(df, ["a", "c"], "double")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        None
        ```
        !!! success "Conclusion: Columns are of type."
        </div>

        ```{.py .python linenums="1" title="Example 2: Warning raised"}
        >>> warn_columns_invalid_type(df, ["a", "b"], "double")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        InvalidPySparkDataTypeWarning: Columns ['a', 'b'] are types ['int', 'string'], which are not the required type: 'double'.
        ```
        !!! failure "Conclusion: Columns are not of type."
        </div>

    ??? tip "See Also"
        - [`column_is_type`][toolbox_pyspark.checks.column_is_type]
        - [`columns_are_type`][toolbox_pyspark.checks.columns_are_type]
        - [`assert_column_is_type`][toolbox_pyspark.checks.assert_column_is_type]
        - [`assert_columns_are_type`][toolbox_pyspark.checks.assert_columns_are_type]
        - [`warn_column_invalid_type`][toolbox_pyspark.checks.warn_column_invalid_type]
        - [`warn_columns_invalid_type`][toolbox_pyspark.checks.warn_columns_invalid
    """
    result, invalid_types = _columns_are_type(dataframe, columns, datatype, match_case)
    if not result:
        warn(
            f"Columns {[col for col, _ in invalid_types]} are types {[typ for _, typ in invalid_types]}, "
            f"which are not the required type: '{datatype}'.",
            InvalidPySparkDataTypeWarning,
        )

Table Existence🔗

Summary

The checks module is used to check and validate various attributed about a given pyspark dataframe.

table_exists 🔗

table_exists(
    name: str,
    path: str,
    data_format: SPARK_FORMATS,
    spark_session: SparkSession,
) -> bool

Summary

Will try to read table from path using format, and if successful will return True otherwise False.

Parameters:

Name Type Description Default
name str

The name of the table to check exists.

required
path str

The directory where the table should be existing.

required
data_format str

The format of the table to try checking.

required
spark_session SparkSession

The spark session to use for the importing.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

Returns True if the table exists, False otherwise.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.io import write_to_path
>>> from toolbox_pyspark.checks import table_exists
>>>
>>> # Constants
>>> write_name = "test_df"
>>> write_path = f"./test"
>>> write_format = "parquet"
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )
>>>
>>> # Write data
>>> write_to_path(df, f"{write_name}.{write_format}", write_path)

Example 1: Table exists
1
>>> table_exists("test_df.parquet", "./test", "parquet", spark)
Terminal
True

Conclusion: Table exists.

Example 2: Table does not exist
1
>>> table_exists("bad_table_name.parquet", "./test", "parquet", spark)
Terminal
False

Conclusion: Table does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
@typechecked
def table_exists(
    name: str,
    path: str,
    data_format: SPARK_FORMATS,
    spark_session: SparkSession,
) -> bool:
    """
    !!! note "Summary"
        Will try to read `#!py table` from `#!py path` using `#!py format`, and if successful will return `#!py True` otherwise `#!py False`.

    Params:
        name (str):
            The name of the table to check exists.
        path (str):
            The directory where the table should be existing.
        data_format (str):
            The format of the table to try checking.
        spark_session (SparkSession):
            The `#!py spark` session to use for the importing.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            Returns `#!py True` if the table exists, `False` otherwise.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.io import write_to_path
        >>> from toolbox_pyspark.checks import table_exists
        >>>
        >>> # Constants
        >>> write_name = "test_df"
        >>> write_path = f"./test"
        >>> write_format = "parquet"
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Write data
        >>> write_to_path(df, f"{write_name}.{write_format}", write_path)
        ```

        ```{.py .python linenums="1" title="Example 1: Table exists"}
        >>> table_exists("test_df.parquet", "./test", "parquet", spark)
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: Table exists."
        </div>

        ```{.py .python linenums="1" title="Example 2: Table does not exist"}
        >>> table_exists("bad_table_name.parquet", "./test", "parquet", spark)
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: Table does not exist."
        </div>

    ??? tip "See Also"
        - [`assert_table_exists`][toolbox_pyspark.checks.assert_table_exists]
    """
    try:
        _ = read_from_path(
            name=name,
            path=path,
            data_format=data_format,
            spark_session=spark_session,
        )
    except Exception:
        return False
    return True

assert_table_exists 🔗

assert_table_exists(
    name: str,
    path: str,
    data_format: SPARK_FORMATS,
    spark_session: SparkSession,
) -> None

Summary

Assert whether a table exists at a given path using data_format.

Parameters:

Name Type Description Default
name str

The name of the table to check exists.

required
path str

The directory where the table should be existing.

required
data_format str

The format of the table to try checking.

required
spark_session SparkSession

The spark session to use for the importing.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

TableDoesNotExistError

If the table does not exist at the specified location.

Returns:

Type Description
type(None)

Nothing is returned. Either an TableDoesNotExistError exception is raised, or nothing.

Examples
Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.io import write_to_path
>>> from toolbox_pyspark.checks import assert_table_exists
>>>
>>> # Constants
>>> write_name = "test_df"
>>> write_path = f"./test"
>>> write_format = "parquet"
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )
>>>
>>> # Write data
>>> write_to_path(df, f"{write_name}.{write_format}", write_path)

Example 1: Table exists
1
>>> assert_table_exists("test_df.parquet", "./test", "parquet", spark)
Terminal
None

Conclusion: Table exists.

Example 2: Table does not exist
1
>>> assert_table_exists("bad_table_name.parquet", "./test", "parquet", spark)
Terminal
TableDoesNotExistError: Table 'bad_table_name.parquet' does not exist at path './test'.

Conclusion: Table does not exist.

See Also
Source code in src/toolbox_pyspark/checks.py
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
@typechecked
def assert_table_exists(
    name: str,
    path: str,
    data_format: SPARK_FORMATS,
    spark_session: SparkSession,
) -> None:
    """
    !!! note "Summary"
        Assert whether a table exists at a given `path` using `data_format`.

    Params:
        name (str):
            The name of the table to check exists.
        path (str):
            The directory where the table should be existing.
        data_format (str):
            The format of the table to try checking.
        spark_session (SparkSession):
            The `#!py spark` session to use for the importing.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        TableDoesNotExistError:
            If the table does not exist at the specified location.

    Returns:
        (type(None)):
            Nothing is returned. Either an `#!py TableDoesNotExistError` exception is raised, or nothing.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.io import write_to_path
        >>> from toolbox_pyspark.checks import assert_table_exists
        >>>
        >>> # Constants
        >>> write_name = "test_df"
        >>> write_path = f"./test"
        >>> write_format = "parquet"
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Write data
        >>> write_to_path(df, f"{write_name}.{write_format}", write_path)
        ```

        ```{.py .python linenums="1" title="Example 1: Table exists"}
        >>> assert_table_exists("test_df.parquet", "./test", "parquet", spark)
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        None
        ```
        !!! success "Conclusion: Table exists."
        </div>

        ```{.py .python linenums="1" title="Example 2: Table does not exist"}
        >>> assert_table_exists("bad_table_name.parquet", "./test", "parquet", spark)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        TableDoesNotExistError: Table 'bad_table_name.parquet' does not exist at path './test'.
        ```
        !!! failure "Conclusion: Table does not exist."
        </div>

    ??? tip "See Also"
        - [`table_exists`][toolbox_pyspark.checks.table_exists]
    """
    if not table_exists(
        name=name, path=path, data_format=data_format, spark_session=spark_session
    ):
        raise TableDoesNotExistError(f"Table '{name}' does not exist at path '{path}'.")