Frozen Dataclasses

Concepts covered: Functional Transforms

A pipeline hands each record from step to step, and Python passes a reference to the same object every time. If any step changes the record in place, every variable, list and earlier result holding that reference sees the change. Knowing what a record contains at a given line then means tracing every place it has been.

The bug a shared record causes

class Like:
    def __init__(self, user, post, weight):
        self.user = user
        self.post = post
        self.weight = weight

def boost_new_users(like):
    like.weight = like.weight * 2
    return like

raw = [Like("ana", "p1", 1), Like("bo", "p1", 1)]
boosted = [boost_new_users(like) for like in raw]

print(sum(like.weight for like in boosted))
print(sum(like.weight for like in raw))

Output:

4
4

The raw total should still be 2. boost_new_users changed the object it received and returned that same object, so raw and boosted are 2 lists of the same 2 records. The comprehension looks like it builds new values, and nothing at the call site says otherwise.

Sealing a record with frozen=True

The standard library module dataclasses writes the routine parts of a record class. Put @dataclass(frozen=True) above a class with annotated fields and Python generates __init__, __repr__ and __eq__ from those fields, plus a __setattr__ that raises FrozenInstanceError on any assignment. The Decorators section below explains how the @ line works; for now, what matters is the sealed class it produces.

from dataclasses import dataclass, replace, FrozenInstanceError

@dataclass(frozen=True)
class Like:
    user: str
    post: str
    weight: int

like = Like("ana", "p1", 1)
print(like)

try:
    like.weight = 2
except FrozenInstanceError as err:
    print("refused:", err)

boosted = replace(like, weight=like.weight * 2)
print(boosted)
print(like)
print(like == Like("ana", "p1", 1))

Output:

Like(user='ana', post='p1', weight=1)
refused: cannot assign to field 'weight'
Like(user='ana', post='p1', weight=2)
Like(user='ana', post='p1', weight=1)
True

replace builds a new instance with the named fields changed and every other field carried over. The original like still reports weight 1 and will for as long as it exists, so a step that read it before the boost is unaffected.

What a pipeline gains from frozen records

Guarantees a frozen record gives you

from dataclasses import dataclass

@dataclass(frozen=True)
class Like:
    user: str
    post: str
    weight: int

stream = [Like("ana", "p1", 1), Like("bo", "p1", 1), Like("ana", "p1", 1)]
print(len(set(stream)))

seen = {}
for like in stream:
    seen[like] = seen.get(like, 0) + 1
print(seen[Like("ana", "p1", 1)])

Output:

2
2

The set keeps 2 records because ana's repeated like hashes and compares equal to her first. Objects of a plain class without __eq__ compare by identity, so a set of them would keep all 3.

Frozen stops at the first level

frozen=True blocks assigning to a field. It does nothing to the object a field points at. A list stored in a frozen record can still be appended to, and the record's contents change while assignment to the field is still refused. This is the shallow-copy problem from the lists lessons, inside a record.

from dataclasses import dataclass

@dataclass(frozen=True)
class Post:
    post_id: str
    tags: list

post = Post("p1", ["cats"])
post.tags.append("dogs")
print(post)

@dataclass(frozen=True)
class SafePost:
    post_id: str
    tags: tuple

print(SafePost("p1", ("cats",)))

Output:

Post(post_id='p1', tags=['cats', 'dogs'])
SafePost(post_id='p1', tags=('cats',))

The list field also breaks hashing: hash(post) raises TypeError: unhashable type: 'list', so a Post cannot go in a set or serve as a cache key. Swapping the list for a tuple fixes both problems.

What does this program print?

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Batch:
    name: str
    ids: list

a = Batch("morning", [1, 2])
b = replace(a, name="evening")
b.ids.append(3)
print(a.ids)

The fix for the shared-record bug is a step that returns a new record and leaves its input alone. With frozen records, replace is how such a step changes a field, and map applies the step across a batch.

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Like:
    user: str
    post: str
    weight: int

def normalize(like):
    return replace(like, user=like.user.lower())

raw = [Like("Ana", "p1", 1), Like("bo", "p1", 1)]
clean = list(map(normalize, raw))

print([like.user for like in clean])
print([like.user for like in raw])
print(clean[0] is raw[0], clean[1] == raw[1])

Output:

['ana', 'bo']
['Ana', 'bo']
False True

Every call to replace builds a new instance, even when no field changes value: bo's cleaned record compares equal to the original yet is a separate object. raw still holds the casing it arrived with, so a later step that needs the original spelling, such as one that audits the source data, reads it unchanged. Testing normalize means checking its return value and nothing else.

About this lesson

This section is part of the Functional Programming: Advanced 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.