Table of Contents
- Prerequisites
- Concept: Why encapsulate Spark logic
- Exercise 1: A reusable SparkSession wrapper class
- Exercise 2: A DataFrame operations class
- Concept: Metaclasses
- Exercise 3: Metaclass-registered ETL steps
- Fix or extend challenge
- Verification checklist
- Clean up
Prerequisites
- An Azure Databricks workspace with Unity Catalog and Serverless compute (as provisioned in LA-01-Explore-Azure-Databricks).
- Familiarity with PySpark DataFrame operations from LA-03-Transform-data.
- The
products.csvandsalesdata used in earlier labs.
Python for Spark (PySpark) notes run on serverless compute. For this lab any compute that runs Python 3.11+ with Spark 3.5.x is sufficient.
Concept: Why encapsulate Spark logic
Notebooks encourage copy-pasted, ad-hoc transformations. Reusable classes give you:
- Encapsulation — DataFrame logic lives in one place; notebooks just orchestrate.
- State management — session parameters, catalog/schema defaults, and runtime configuration are set once.
- Testability — pure methods on classes can be unit-tested outside notebooks.
- Metaclass automation — repetitive patterns (e.g. “every ETL step must register itself and log its name”) can be enforced at class creation time, not at runtime.
Exercise 1: A reusable SparkSession wrapper class
-
In your workspace, select (+) New → Notebook, name it LA-07-classes-metaclasses, attach it to Serverless compute.
-
In the first cell, define a singleton-style wrapper that centralizes session creation and catalog defaults:
class SparkSessionWrapper:
"""Centralizes Spark session access and catalog defaults.
Uses __new__ to guarantee one instance per notebook session.
"""
_instance = None
def __new__(cls, catalog: str = None, schema: str = "default"):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.catalog = catalog
cls._instance.schema = schema
return cls._instance
@property
def spark(self):
# Databricks notebooks already provide `spark`;
# the wrapper guarantees consistent configuration.
spark.conf.set("spark.databricks.delta.formatCheck.enabled", "true")
return spark
def table(self, name: str) -> str:
return f"{self.catalog}.{self.schema}.{name}"
def read_csv(self, path: str, **kwargs):
default = {"header": "true", "inferSchema": "true"}
return self.spark.read.options(**{**default, **kwargs}).csv(path)- Test the wrapper:
wrapper = SparkSessionWrapper(catalog="main", schema="default")
a = SparkSessionWrapper()
b = SparkSessionWrapper(catalog="other")
print(a is b) # True — singleton enforced
print(wrapper.table("products")) # main.default.productsExpected output:
True
main.default.productsOn Databricks,
sparkis a provided variable in Python cells; the wrapper does not callSparkSession.builderbecause the cluster session already exists. On other environments thesparkproperty would build the session instead.
Exercise 2: A DataFrame operations class
- Add a cell with a class that wraps common DataFrame operations so analysts call one well-named method instead of chains:
from pyspark.sql import DataFrame, functions as F
class DataFrameOps:
"""Reusable, chainable DataFrame transformations."""
def __init__(self, df: DataFrame):
self.df = df
def dedupe(self, keys: list) -> "DataFrameOps":
self.df = self.df.dropDuplicates(keys)
return self
def fill_nulls(self, mapping: dict) -> "DataFrameOps":
self.df = self.df.fillna(mapping)
return self
def summarize(self, group: str, agg_col: str) -> DataFrame:
return (self.df
.groupBy(group)
.agg(F.sum(agg_col).alias(f"total_{agg_col}"),
F.count("*").alias("rows"))
.orderBy(group))- Use it against the products table:
df = wrapper.spark.table("products")
result = DataFrameOps(df).dedupe(["ProductID"]).summarize("Category", "ListPrice")
display(result)Expected output: one row per category with total_Price and rows, e.g.
Category | total_Price | rows
--------------+-------------+-----
Accessories | 1240.75 | 18
Laptops | 9870.00 | 12- Verify: run the summarize against the raw table without
dedupeand confirmrowsis greater or equal — proving the wrapper chain applied correctly.
Concept: Metaclasses
A metaclass is the class of a class: Python calls it when the class statement executes, letting you inspect or modify the class before it exists. Common Spark uses:
- Auto-registration — collect every ETL step class into a registry without manual bookkeeping.
- Method injection — add standard methods (e.g.
run(),describe()) to every subclass automatically. - Contract enforcement — fail fast at import time if a subclass forgets a required attribute.
Key points to remember:
typeis the default metaclass;class Foo(metaclass=MyMeta)overrides it.MyMeta.__new__(mcls, name, bases, ns)receives the class name, base classes, and namespace dict.- Prefer metaclasses only when inheritance alone cannot express the requirement.
Exercise 3: Metaclass-registered ETL steps
- Add a cell defining a registry metaclass and a base step:
class StepMeta(type):
"""Registers every subclass and injects a describe() method."""
registry: dict[str, type] = {}
def __new__(mcls, name, bases, ns):
cls = super().__new__(mcls, name, bases, ns)
if bases: # skip the abstract base itself
if "name" not in ns:
raise TypeError(f"{name} must define a 'name' attribute")
mcls.registry[ns["name"]] = cls
def describe(self):
return f"step={self.name!r} params={self.params}"
cls.describe = describe
return cls
class ETLStep(metaclass=StepMeta):
name: str = None
params: dict = {}
def run(self, df): # subclasses override
raise NotImplementedError- Implement two concrete steps that register automatically:
class CleanPrices(ETLStep):
name = "clean_prices"
params = {"min_price": 0.0}
def run(self, df):
return df.filter(F.col("ListPrice") > self.params["min_price"])
class RevenueByCategory(ETLStep):
name = "revenue_by_category"
params = {"group": "Category"}
def run(self, df):
return df.groupBy(self.params["group"]).agg(
F.sum("ListPrice").alias("revenue"))- Drive the pipeline from the registry — no hard-coded class names:
df = wrapper.spark.table("products")
pipeline = [StepMeta.registry["clean_prices"](), StepMeta.registry["revenue_by_category"]()]
for step in pipeline:
df = step.run(df)
print(step.describe())
display(df)Expected output:
step='clean_prices' params={'min_price': 0.0}
step='revenue_by_category' params={'group': 'Category'}followed by the revenue table by category.
- Verify the contract enforcement — this must fail with
TypeError:
class BrokenStep(ETLStep):
params = {"x": 1}
def run(self, df):
return dfExpected output:
TypeError: BrokenStep must define a 'name' attributeFix or extend challenge
The following wrapper has a deliberate bug — every instance shares the same mutable defaults, so the second wrapper “remembers” the first one’s tables. Find it and fix it:
class BrokenWrapper:
shared_tables = []
def add_table(self, name):
self.shared_tables.append(name)
w1 = BrokenWrapper()
w1.add_table("products")
w2 = BrokenWrapper()
w2.add_table("sales")
print(w1.shared_tables) # ['products', 'sales'] — wrong!Extend: add a
StepMeta.before_registerhook that logsf"registering {name}", and makeDataFrameOpsa context manager (__enter__/__exit__) that unpersists cached DataFrames on exit.
Verification checklist
-
SparkSessionWrapper()returns the same instance on repeated calls. -
DataFrameOpschainsdedupe→summarizeand produces correct aggregates. -
StepMeta.registrycontainsclean_pricesandrevenue_by_category. - A subclass missing
nameraisesTypeErrorat class definition time. - The challenge bug is explained (class attribute vs instance attribute) and fixed.
Clean up
The notebook only reads existing tables, so no billable data was created. If you attached a dedicated compute, terminate it:
- In the notebook toolbar, select the compute dropdown → Detach.
- In Compute in the sidebar, confirm no idle clusters remain running.