PySpark style guide
Write transformations that make their inputs, outputs, null behavior, and execution boundary easy to review. Prefer Spark's public DataFrame and SQL APIs. A reader should be able to compose a transformation without starting a Spark session or running a job.
The example targets CPython 3.11.18, PySpark 3.5.8, and Eclipse Temurin 17.0.21.1+2, the tuple used for the portal's separately verified getting- started example. This is not a support claim for every PySparky repository. Check the relevant project's compatibility table before choosing versions.
Use explicit imports and useful types
Import the public objects a function uses. Alias the SQL functions module as
F, and use Column and DataFrame to show whether a function builds an
expression or transforms a frame.
from pyspark.sql import Column, DataFrame, functions as F
def normalise_label(value: Column) -> Column:
"""Collapse runs of whitespace and trim a label expression."""
return F.trim(F.regexp_replace(value, r"\s+", " "))
def non_negative_amount(amount: Column) -> Column:
"""Return whether an amount is non-negative; treat NULL as false."""
return F.coalesce(amount >= F.lit(0.0), F.lit(False))
Use descriptive names that distinguish a Python value from a Spark
expression. amount: Column is not a Python float: it describes an expression
Spark will evaluate for rows. Avoid wildcard imports and mutable module-level
Spark state. Use F.lit(value) when a Python value is meant to be a literal in
an expression.
Prefer F.col("name") for column references. For unusual names containing a
dot or backtick, follow Spark's column reference syntax
and quote the identifier deliberately; a dot can otherwise mean nested-field
access.
Compose expression and frame functions
A column helper should build and return a Column. A frame transformation
should accept and return a DataFrame. Keep these ordinary functions free of
actions, session creation, network calls, and writes so callers can compose
them and choose when to execute the resulting plan.
from pyspark.sql import Column, DataFrame, functions as F
def normalise_label(value: Column) -> Column:
return F.trim(F.regexp_replace(value, r"\s+", " "))
def clean_events(frame: DataFrame) -> DataFrame:
return frame.select(
F.col("event_id"),
normalise_label(F.col("label")).alias("label"),
F.coalesce(
F.col("amount") >= F.lit(0.0),
F.lit(False),
).alias("amount_is_non_negative"),
)
cleaned = source.transform(clean_events)
DataFrame.transform
applies a DataFrame-in/DataFrame-out function and returns its result. Use
select when it makes the output columns and expressions clear. Use
withColumns
for a group of independent expressions when the project's minimum Spark
version supports it. Put dependent expressions in separate stages so each
stage refers to columns that already exist.
Decide null behavior explicitly
Spark SQL comparisons use three-valued logic: comparing NULL with an ordinary
value produces NULL (unknown), not False. A filter keeps rows only when its
condition is true. Decide whether an unknown result should be retained,
rejected, or reported, then encode that policy with coalesce, isNull, or a
separate result column.
Use Column.eqNullSafe
only when the domain meaning requires two nulls to compare as equal. It changes
comparison semantics; it is not a general replacement for ==.
SQL NULL and floating-point NaN are different values. isNull() checks for
SQL nulls; use isnan
when the input is floating point and the domain needs a NaN policy. Test both
cases when missing or invalid numeric values affect results.
Keep execution visible
Operations such as select, filter, join, and withColumn build a
DataFrame plan. They do not return the transformed rows. Actions such as
show, count, collect, and writes evaluate work. Keep actions at the
application boundary rather than inside reusable expression or transformation
functions.
collect() and toPandas() transfer results to the driver. Use them only
when the result is known to be bounded. A count() can start a job even though
it returns only one number. Use explain() to inspect a plan; use measured
actions and representative data when evaluating runtime behavior.
Create SparkSession explicitly in an application or test, and pass required
configuration and inputs to functions. Keep reading and writing separate from
the transformation itself. If a function caches, checkpoints, collects, or
performs I/O, make that behavior part of its name and documentation.
Prefer native expressions when they fit
Use built-in SQL functions and higher-order functions when they express the operation. Spark can inspect these expressions as part of its plan. A Python UDF is useful when the behavior cannot reasonably be expressed with available Spark functions, but it introduces a Python execution boundary and requires clear input, output, and null contracts. A pandas UDF uses Arrow and pandas; account for those runtime dependencies and its batch-oriented semantics. Benchmark the actual workload before making performance claims. A UDF is not automatically wrong, and no UDF form is universally faster.
See Spark's documentation for Python UDFs and pandas UDFs.
Make data contracts and ordering explicit
- Supply an explicit schema at external data boundaries when inference could vary or lose required type and nullability information.
- Alias columns after joins so the output schema has unambiguous names. Select the intended output instead of leaving duplicate key columns implicit.
- Define a complete tie-breaker before selecting a “latest” row. A
dropDuplicatescall does not express which competing row is the business winner. - DataFrames have no guaranteed row order. Specify an order for user-visible output and use stable keys when a test needs ordered comparison.
- Set and test the session time zone for timestamp-sensitive behavior. Test parsing and boundaries with the Spark version and ANSI settings used by the application.
Run a small example
This standalone script defines its schema, includes both SQL null and an ordinary value, builds the transformation lazily, and makes the action visible at the call site. It uses synthetic local data.
from pyspark.sql import Column, DataFrame, SparkSession, functions as F, types as T
def normalise_label(value: Column) -> Column:
return F.trim(F.regexp_replace(value, r"\s+", " "))
def clean_events(frame: DataFrame) -> DataFrame:
return frame.select(
F.col("event_id"),
normalise_label(F.col("label")).alias("label"),
F.coalesce(
F.col("amount") >= F.lit(0.0),
F.lit(False),
).alias("amount_is_non_negative"),
)
schema = T.StructType(
[
T.StructField("event_id", T.LongType(), nullable=False),
T.StructField("label", T.StringType(), nullable=True),
T.StructField("amount", T.DoubleType(), nullable=True),
]
)
events = [
(1, " ready now ", 12.5),
(2, None, None),
(3, "chargeback", -2.0),
]
spark = (
SparkSession.builder.master("local[1]")
.appName("pysparky-style-guide")
.config("spark.ui.enabled", "false")
.getOrCreate()
)
try:
source = spark.createDataFrame(events, schema)
cleaned = source.transform(clean_events)
cleaned.orderBy("event_id").show(truncate=False) # action; executes the plan
finally:
spark.stop()
The null amount produces false because this example chose that policy in
coalesce. Change the expression if missing amounts should remain unknown or
be rejected separately. The policy belongs in the data contract, not in an
assumption about Spark's comparison result.