Custom Structures

Concepts covered: Dataclasses

The join step loads every booking into memory before matching it to listings. With a few million bookings, the bytes each record's container costs decide whether the job fits on its machine. A dict per record is the default and also the largest option: each dict carries its own hash table, sized with room to grow, even though every record has the same 4 keys.

import sys
from collections import namedtuple

class BookingObj:
    def __init__(self, booking_id, guest, city, price):
        self.booking_id = booking_id
        self.guest = guest
        self.city = city
        self.price = price

class BookingSlots:
    __slots__ = ("booking_id", "guest", "city", "price")

    def __init__(self, booking_id, guest, city, price):
        self.booking_id = booking_id
        self.guest = guest
        self.city = city
        self.price = price

BookingTuple = namedtuple("BookingTuple", ["booking_id", "guest", "city", "price"])

as_dict = {"booking_id": 501, "guest": "g42", "city": "Lisbon", "price": 120.0}
as_obj = BookingObj(501, "g42", "Lisbon", 120.0)
as_slots = BookingSlots(501, "g42", "Lisbon", 120.0)
as_tuple = BookingTuple(501, "g42", "Lisbon", 120.0)

print("dict:  ", sys.getsizeof(as_dict))
print("object:", sys.getsizeof(as_obj) + sys.getsizeof(as_obj.__dict__))
print("slots: ", sys.getsizeof(as_slots))
print("tuple: ", sys.getsizeof(as_tuple))

Output:

dict:   232
object: 152
slots:  64
tuple:  72

These figures come from 64-bit CPython 3.9 and cover each container alone. The strings and numbers inside are separate objects, and the next section measures them. A regular class keeps its attributes in a per-instance __dict__, so every instance pays for an object plus a dict. The slots class and the namedtuple both store 4 references in a fixed row; the namedtuple adds an 8-byte length field, so it measures 72 to the slots class's 64.

Fixed attributes with __slots__

Assigning a tuple of names to __slots__ in the class body tells Python to reserve exactly those attributes in each instance, with no __dict__ behind them. Reading and writing them works as before. Creating any other attribute raises AttributeError, which turns a misspelled field name into an error on the line that misspelled it.

class BookingSlots:
    __slots__ = ("booking_id", "guest", "city", "price")

    def __init__(self, booking_id, guest, city, price):
        self.booking_id = booking_id
        self.guest = guest
        self.city = city
        self.price = price

    def __repr__(self):
        return f"BookingSlots({self.booking_id}, {self.city!r}, {self.price})"

b = BookingSlots(501, "g42", "Lisbon", 120.0)
b.price = 99.0
print(b)
try:
    b.prcie = 80.0
except AttributeError as e:
    print("AttributeError:", e)
print(hasattr(b, "__dict__"))

Output:

BookingSlots(501, 'Lisbon', 99.0)
AttributeError: 'BookingSlots' object has no attribute 'prcie'
False

Without a __repr__, printing an instance shows its class name and memory address, which changes on every run. A record type that ends up in logs needs one.

This class has no __slots__. What does the program print?

class Booking:
    def __init__(self, booking_id, price):
        self.booking_id = booking_id
        self.price = price

b = Booking(501, 120.0)
b.prcie = 99.0
print(b.price)

namedtuple: a tuple with field names

collections.namedtuple builds a tuple subclass whose positions also have names. It costs the same as a plain tuple, prints its fields, and unpacks like any tuple. Because it is immutable, it can be a dict key or a set member whenever its fields are hashable. Changing a field means building a new record with _replace, which leaves the original untouched.

from collections import namedtuple

Booking = namedtuple("Booking", ["booking_id", "guest", "city", "price"])
b = Booking(501, "g42", "Lisbon", 120.0)
print(b)
print(b.city, b[2])
discounted = b._replace(price=96.0)
print(discounted.price, b.price)
print(discounted._asdict())
try:
    b.price = 96.0
except AttributeError as e:
    print("AttributeError:", e)

Output:

Booking(booking_id=501, guest='g42', city='Lisbon', price=120.0)
Lisbon Lisbon
96.0 120.0
{'booking_id': 501, 'guest': 'g42', 'city': 'Lisbon', 'price': 96.0}
AttributeError: can't set attribute

Enforcing the schema where rows enter

Rows usually arrive as dicts, decoded from JSON or built by an earlier step. Converting them with Booking(**row) at the point where they enter the job does 2 things at once: it shrinks each record, and it rejects any row whose keys differ from the declared fields, before that row reaches the join.

from collections import namedtuple

Booking = namedtuple("Booking", ["booking_id", "guest", "city", "price"])
rows = [
    {"booking_id": 501, "guest": "g42", "city": "Lisbon", "price": 120.0},
    {"booking_id": 502, "guest": "g17", "city": "Porto", "price": 85.0, "promo": "SPRING"},
]
for row in rows:
    try:
        print(Booking(**row))
    except TypeError as e:
        print("rejected", row["booking_id"], "->", e)

Output:

Booking(booking_id=501, guest='g42', city='Lisbon', price=120.0)
rejected 502 -> __new__() got an unexpected keyword argument 'promo'
Record typeBytes, 4 fieldsChange a field?Add a field later?Fits when
dict232YesYesRows arrive with varying keys or go straight to JSON
regular class152YesYesYou need methods and hold few instances
class with `__slots__`64YesNoMillions of mutable records share one schema
namedtuple72NoNoFixed records you read, group or use as keys

About this lesson

This section is part of the Data Structures: 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.