Check your understanding of the previous reading: which operators work with dataclass instances, when two instances are equivalent, and how to annotate the types in a function that consumes and returns a dataclass.

Question 1

Which of the following operators work with dataclass instances?

Select every option that applies, then check.

  • Not quite. Addition and the other math operators raise a TypeError on dataclass instances.
  • Not quite. Like addition, subtraction is a math operator and doesn't work on dataclass instances.
  • Not quite. Dataclass fields are accessed by name with a period (instance.field), not by position with square brackets.
  • Correct. Equality (and inequality) compares two instances field by field.
  • Not quite. Ordering operators like < also raise a TypeError - only equality and inequality work.
  • Not quite. Modulo is a math operator, just like addition and subtraction, and doesn't work on dataclass instances.

Question 2

When are two dataclass instances equivalent (==)?

Select one answer, then check.

  • Not quite. The dataclass itself matters too - two different dataclasses with the same field values are not equivalent.
  • Correct. Equality checks both the class and every field's value.
  • Not quite. All fields are checked, not just one - a single matching field isn't enough.
  • Not quite. Unlike the math and ordering operators, == works fine on dataclass instances.
  • Not quite. == does not error, but two instances with matching class and fields do compare equal.

Question 3

Given the code below:

from dataclasses import dataclass
from bakery import assert_equal

@dataclass
class Fruit:
    kind: str
    sweetness: __1__

def is_sweet(fruit: __2__) -> __3__:
    return fruit.sweetness > 10

assert_equal(is_sweet(Fruit("Orange", 15)), True)
assert_equal(is_sweet(Fruit("Lemon", 5)), False)

The sweetness field's type (__1__) should be . The fruit parameter's type (__2__) should be . The is_sweet function's return type (__3__) should be .

Word bank — not all words are used