Nulls and Types
NULL arrives as None
Spark hands a SQL NULL to a UDF as Python None. The first price_band compares price < 50 before anything else, and in Python 3 that comparison on None raises TypeError: '<' not supported between instances of 'NoneType' and 'int'. The practice products table has products with no price, so applying that UDF to every row fails.
Because transformations are lazy, the withColumn line succeeds. The error surfaces at the first action, as a failed task whose message ends in the Python traceback. Spark retries the task, the retry meets the same None, and the job fails.
from pyspark.sql import functions as F
@F.udf(returnType="string")
def price_band(price):
if price is None:
return None
if price < 50:
return "budget"
if price < 200:
return "mid"
return "premium"Returning None puts a NULL in the column, so a missing price stays visible as missing. A label such as "unknown" is also valid when downstream reports need a value in every row. Choose one deliberately and write the choice into the column's documentation.
The check belongs inside the function
A where(F.col("price").isNotNull()) ahead of the UDF looks like protection, and in many plans it works. Spark's documentation states that it does not guarantee the order in which subexpressions are evaluated, including the order of WHERE and HAVING clauses, and that a UDF relying on a SQL null check is not guaranteed to see that check run first. A check at the top of the function holds however Catalyst arranges the plan.
The declared type is a promise
Spark sets the column's type from the declaration, then converts each object the function returns into that type. With the default settings, an object of the wrong Python type becomes NULL, and Spark raises neither an error nor a warning. The schema still reads double and every task succeeds. The bad values show up later as gaps in a report.
| Function returns | Declared type | Value in the column |
|---|---|---|
| `18.0` (float) | `double` | `18.0` |
| `18` (int) | `double` | NULL |
| `"18.0"` (str) | `double` | NULL |
| `18.0` (float) | `string`, the default | `"18.0"`, as text |
| `None` | any type | NULL |
The usual form of this bug is a branch that returns a whole number where the declaration says double.
@F.udf(returnType="double")
def member_discount(price):
if price is None:
return None
if price > 100:
return round(price * 0.10, 2)
return 0The fix is on the Python side: make every branch return the declared type. Here that means return 0.0, and a computed value can be wrapped in float(...). After the first run, count the NULLs in each UDF column and compare that count with the NULLs in its inputs. A gap means a branch is returning the wrong type.
The UDF runs on 10 rows where every units and baskets value is a positive whole number. What does its output column hold?
@F.udf(returnType="int")
def units_per_basket(units, baskets):
if units is None or baskets in (None, 0):
return None
return units / baskets- NULL in every row, because / returns a Python float and the declared type is int
- Each quotient rounded down, because Spark casts every float to the declared int
- Each quotient as text, because a mismatched value falls back to the string default
- Nothing, because the first row raises a type error and the job fails at the action
The first price_band has no None check, and the practice products table has products with no price. Which change keeps the job from failing on those rows, whatever order Catalyst gives the plan?
- Add .where(F.col("price").isNotNull()) before the UDF, since a filter always runs before later expressions
- Test price == 0 at the top and return None, since Spark passes a NULL price into the function as 0
- Return None when price is None on the first line of the function, before any comparison runs
- Declare returnType="double", since a type mismatch turns every failure inside the function into a NULL
About this lesson
This section is part of the UDFs and Serialization: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.