Month, tests written
firstAdd leap-year support to
Month, so February allows 29 days when theBirthDate’sYearis a leap year. Write the tests first.
Enums
Are Types Too shows Month checking a day
against its cap. The cap now depends on a second value, so
check_day() needs the Year as well,
and Year needs a method that applies the leap rule.
Write the pytest tests first, covering a leap year,
a common year, the leap century 2000, and a day that fails in
every year. Year accepts 1901 through the current
year, so it rejects 1900 and 2100, the common century years.
your pytest tests pass and cover four cases:
February 29 accepted in 2020 and in 2000, February 29 rejected
in 2021 with a TypeFailure, and February 30
rejected in 2020. If you delete the divisible-by-400 part of
your leap rule, the 2000 test fails.
If you drop the % 400 clause from
is_leap(), every century year counts as common.
check_day() then raises a TypeFailure
for Day(29) in 2000, and
test_feb_29_allowed_in_2000 fails.
An is_leap() that tests divisibility by 4 alone
passes all four tests, because the range Year
accepts holds one century year, 2000. The solution still writes
the full rule, because Year’s upper bound follows
date.today(). Once 2100 arrives, Year
will accept it, and 2100 is a common year.
# test_ch12_leap_year.py
from dataclasses import dataclass
from datetime import date
from enum import Enum
from typing import Final
import pytest
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
@dataclass(frozen=True)
class Day:
n: int
def __post_init__(self) -> None:
check(1 <= self.n <= 31, f"Day({self.n})")
@dataclass(frozen=True)
class Year:
n: int
def __post_init__(self) -> None:
check(1900 < self.n <= date.today().year,
f"Year({self.n})")
def is_leap(self) -> bool:
return self.n % 4 == 0 and (
self.n % 100 != 0 or self.n % 400 == 0)
DAYS: Final[tuple[int, ...]] = (31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31)
class Month(Enum):
JANUARY = 1
FEBRUARY = 2
MARCH = 3
APRIL = 4
MAY = 5
JUNE = 6
JULY = 7
AUGUST = 8
SEPTEMBER = 9
OCTOBER = 10
NOVEMBER = 11
DECEMBER = 12
@property
def max_days(self) -> int:
return DAYS[self.value - 1]
def check_day(self, day: Day, year: Year) -> None:
max_days = self.max_days
if self is Month.FEBRUARY and year.is_leap():
max_days = 29
check(day.n <= max_days, f"Day({day.n})",
f"is past the end of {self.name}")
@dataclass(frozen=True)
class BirthDate:
month: Month
day: Day
year: Year
def __post_init__(self) -> None:
self.month.check_day(self.day, self.year)
def test_feb_29_allowed_in_leap_year() -> None:
bd = BirthDate(Month(2), Day(29), Year(2020))
assert bd.day.n == 29
def test_feb_29_allowed_in_2000() -> None:
bd = BirthDate(Month(2), Day(29), Year(2000))
assert bd.day.n == 29
def test_feb_29_rejected_in_non_leap_year() -> None:
with pytest.raises(TypeFailure):
BirthDate(Month(2), Day(29), Year(2021))
def test_feb_30_always_rejected() -> None:
with pytest.raises(TypeFailure):
BirthDate(Month(2), Day(30), Year(2020))Accept both kinds of leap year.
BirthDate(Month(2), Day(29), Year(2020)) succeeds
because 2020 is divisible by 4 and not by 100. 2000 is divisible
by 100 and also by 400, so it is a leap year too.
Reject a day past the cap. February 30 fails in every year, because February’s cap is 29 at most.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
EmailAddressGive
EmailAddressa stricter check (a single@, with text on both sides). Show the values the check now rejects.
Composing
Types from Types puts the check for
EmailAddress in __post_init__().
Strengthen it there with two calls to check(): one
that counts the @ characters, and one that splits
the text with str.partition() and tests both
halves. The demo feeds EmailAddress each shape the
new check rejects.
# The shape of exercise_2.py
from dataclasses import dataclass
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
@dataclass(frozen=True)
class EmailAddress:
text: str
def __post_init__(self) -> None:
...your exercise_2.py raises a
TypeFailure for "grace",
"b@@x.com", "@x.com",
"b@", and "", and still prints
EmailAddress(text='grace@example.com') for a valid
address. Watch "b@@x.com": it has text on both
sides of its first @.
If you keep only the partition() check,
"b@@x.com" passes. partition() splits
at the first @, and the domain half,
"@x.com", holds text. The demo loop stops there
with an AssertionError, which expect()
raises when the call it makes returns normally. Counting the
@ characters rejects "b@@x.com", so
the solution makes two calls to check().
# exercise_2.py
from dataclasses import dataclass
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
@dataclass(frozen=True)
class EmailAddress:
text: str
def __post_init__(self) -> None:
check(self.text.count("@") == 1,
f"EmailAddress({self.text!r})",
"needs exactly one @")
local, _, domain = self.text.partition("@")
check(len(local) > 0 and len(domain) > 0,
f"EmailAddress({self.text!r})",
"needs text on both sides")
for bad in ["grace", "b@@x.com", "@x.com", "b@", ""]:
expect(TypeFailure, EmailAddress, bad)
#: [TypeFailure] EmailAddress('grace') needs exactly one @
#: [TypeFailure] EmailAddress('b@@x.com') needs exactly one
#: @
#: [TypeFailure] EmailAddress('@x.com') needs text on both
#: sides
#: [TypeFailure] EmailAddress('b@') needs text on both sides
#: [TypeFailure] EmailAddress('') needs exactly one @
print(EmailAddress("grace@example.com"))
#: EmailAddress(text='grace@example.com')Require a single @. The
original check, "@" in self.text, confirms that an
@ appears somewhere and accepts any number of them.
count("@") == 1 rejects both a string with no
@ and a two-@ string like
"b@@x.com".
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
NamedTuple subclass workaround, and the hole it
leavesTake
test_namedtuple_no_hook.py’sStarsand build the subclass workaround: a_Stars(NamedTuple)holding the field, and aStars(_Stars)whose__new__()runs the check. Show thatStars(11)now raises aTypeFailurewhilecopy.replace(Stars(5), number=99)does not, and explain whycopy.replace()on a frozen data class runs the check.
A
NamedTuple Cannot Validate Itself shows that
the class body of a NamedTuple refuses a
__new__(). A subclass is free to define one, so put
the check there and call super().__new__()
afterward. Then find which method copy.replace()
calls on a NamedTuple, and whether that method
calls your __new__().
# The shape of exercise_3.py
import copy
from dataclasses import dataclass
from typing import NamedTuple
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
class _Stars(NamedTuple):
number: int
class Stars(_Stars):
def __new__(cls, number: int) -> Stars:
...your exercise_3.py prints
Stars(number=5), shows Stars(11)
raising a TypeFailure, and prints
Stars(number=99) for
copy.replace(Stars(5), number=99). You can also
name the method copy.replace() calls on a
NamedTuple and say why that call skips your
__new__().
If you define __new__() in the
NamedTuple class body, the class
statement raises an AttributeError, and
Stars stays undefined. The message is
Cannot overwrite NamedTuple attribute __new__. A
NamedTuple Cannot Validate Itself shows the
same failure in its third test. The prohibition covers the class
body that NamedTuple processes. A subclass of that
class is free of it, so the solution defines
__new__() in a subclass.
# exercise_3.py
import copy
from dataclasses import dataclass
from typing import NamedTuple
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
class _Stars(NamedTuple):
number: int
class Stars(_Stars):
def __new__(cls, number: int) -> Stars:
check(1 <= number <= 10, f"Stars({number})")
return super().__new__(cls, number)
print(Stars(5))
#: Stars(number=5)
expect(TypeFailure, Stars, 11)
#: [TypeFailure] Stars(11)
print(Stars(5)._replace(number=99))
#: Stars(number=99)
print(copy.replace(Stars(5), number=99))
#: Stars(number=99)Validate in a subclass. The chapter’s
make_stars() checks the callers that use it, while
a __new__() in the subclass runs on every call to
Stars.
Test the replacement path.
_replace() builds the new tuple through
tuple.__new__(), which skips
Stars.__new__() and its check.
copy.replace() calls _replace(), so it
skips them too. copy.replace() on a validated
Stars therefore produces an unvalidated one. That
gap is worse than no check, because the type now looks like it
guarantees its values.
A frozen data class checks every replacement. On a frozen
data class, copy.replace() calls the constructor,
the constructor calls __post_init__(), and the
check runs.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
from_json() rejects a bad emailFeed
from_json()a JSON string whose email has no@, and confirm that it raisesTypeFailure. The validation you wrote once, inEmailAddress, now also guards your JSON input.
Serializing
to JSON rebuilds a Person from parsed JSON by
calling the field classes. Build a JSON string whose email lacks
an @ with json.dumps(), and pass it to
from_json(). Watch which code raises
TypeFailure: the constructor of
EmailAddress, not from_json().
# The shape of exercise_4.py
import json
from dataclasses import dataclass
from typing import Any
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
@dataclass(frozen=True)
class FullName:
text: str
def __post_init__(self) -> None:
...
@dataclass(frozen=True)
class EmailAddress:
text: str
def __post_init__(self) -> None:
...
@dataclass(frozen=True)
class Person:
name: FullName
email: EmailAddress
def from_json(text: str) -> Person:
...from_json() on your JSON string raises a
TypeFailure reading
EmailAddress('no-at-sign') needs an @ (with your
email text). Uncaught, its traceback runs from
from_json() through
EmailAddress.__post_init__() to the
raise in check().
# exercise_4.py
import json
from dataclasses import dataclass
from typing import Any
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
@dataclass(frozen=True)
class FullName:
text: str
def __post_init__(self) -> None:
check(len(self.text.split()) >= 2,
f"FullName({self.text!r})",
"needs a first and last name")
@dataclass(frozen=True)
class EmailAddress:
text: str
def __post_init__(self) -> None:
check("@" in self.text,
f"EmailAddress({self.text!r})",
"needs an @")
@dataclass(frozen=True)
class Person:
name: FullName
email: EmailAddress
def from_json(text: str) -> Person:
data: dict[str, Any] = json.loads(text)
return Person(
FullName(data["name"]["text"]),
EmailAddress(data["email"]["text"]),
)
bad_json = json.dumps(
{"name": {"text": "Grace Hopper"},
"email": {"text": "no-at-sign"}})
expect(TypeFailure, from_json, bad_json)
#: [TypeFailure] EmailAddress('no-at-sign') needs an @Let the field types validate.
from_json() leaves the email check to
EmailAddress. EmailAddress’s own
__post_init__() runs the same check it runs for any
other caller. One check, inside EmailAddress,
protects every path that constructs a Person, and
the path from untrusted JSON input is one of those.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
__replace__() on an ordinary classMake
copy.replace()work on aStarsthat is not a data class: write an ordinary class holding the rating, validate in__init__(), define__replace__(), and confirm thatcopy.replace()still runs your validation.
Defining
__replace__() shows the method that
copy.replace() calls. In an ordinary class, write
__replace__() so it merges the current field values
with the keyword changes and calls the class constructor.
Because the rebuild goes through __init__(), the
check runs on the replacement.
# The shape of exercise_5.py
import copy
from dataclasses import dataclass
from typing import Self
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
class Stars:
def __init__(self, number: int) -> None:
...
def __repr__(self) -> str:
...
def __replace__(self, **changes: int) -> Self:
...copy.replace() on your Stars(4)
with number=9 returns a Stars holding
9, and with number=99 raises a
TypeFailure from your __init__()
check.
# exercise_5.py
import copy
from dataclasses import dataclass
from typing import Self
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
class Stars:
def __init__(self, number: int) -> None:
check(1 <= number <= 10, f"Stars({number})")
self.number = number
def __repr__(self) -> str:
return f"Stars({self.number})"
def __replace__(self, **changes: int) -> Self:
return type(self)(
**({"number": self.number} | changes))
s = Stars(4)
print(copy.replace(s, number=9))
#: Stars(9)
expect(TypeFailure, copy.replace, s, number=99)
#: [TypeFailure] Stars(99)Merge the changes into the arguments.
copy.replace() looks for __replace__()
and calls it with the keyword changes.
Validate the replacement. The rebuild goes
through __init__(), so the validation runs. A
frozen data class stays validated across a replacement for the
same reason. A __replace__() skips the check if it
copies __dict__ into a new object, the way
copy.copy() does.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
ClassVar counter on a frozen
StarsAdd a
ClassVar[int]counter toStarsthat counts everyStarscreated. Predict whether the counter appears in the generated__init__()’s parameter list, then check by printinginspect.signature(Stars.__init__). Incrementing the counter asStars.built += 1from__post_init__()works on a frozen class, whileself.built += 1does not. Explain why.
A
Real ClassVar shows how @dataclass
treats an annotation marked ClassVar.
@dataclass skips that name when it builds the
fields and the __init__() parameters, so check
fields() and inspect.signature(). For
the frozen question, compare the target of
Stars.built += 1 with the target of
self.built += 1, and ask which of the two targets
frozen=True
guards.
# The shape of exercise_6.py
import inspect
from dataclasses import dataclass, fields
from typing import ClassVar
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
@dataclass(frozen=True)
class Stars:
number: int
built: ClassVar[int] = 0
def __post_init__(self) -> None:
...
@dataclass(frozen=True)
class Wrong:
number: int
built: ClassVar[int] = 0
def __post_init__(self) -> None:
...your exercise_6.py prints
(self, number: int) -> None for
inspect.signature(Stars.__init__) and a count of 3
after building three Stars. A second frozen class
that increments through self fails with
[FrozenInstanceError] cannot assign to field 'built',
and you can say which object that store targets.
# exercise_6.py
import inspect
from dataclasses import dataclass, fields
from typing import ClassVar
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
@dataclass(frozen=True)
class Stars:
number: int
built: ClassVar[int] = 0
def __post_init__(self) -> None:
check(1 <= self.number <= 10,
f"Stars({self.number})")
Stars.built += 1
print([f.name for f in fields(Stars)])
#: ['number']
print(inspect.signature(Stars.__init__))
#: (self, number: int) -> None
for n in (3, 4, 5):
Stars(n)
print(Stars.built)
#: 3
@dataclass(frozen=True)
class Wrong:
number: int
built: ClassVar[int] = 0
def __post_init__(self) -> None:
self.built += 1 # type: ignore
expect(Exception, Wrong, 1)
#: [FrozenInstanceError] cannot assign to field 'built'Keep the counter out of the fields.
@dataclass reads the annotation, sees
ClassVar, and leaves built alone as an
ordinary class attribute, so built stays out of
__init__().
Count on the class. frozen=True
installs a __setattr__() that rejects assignment to
an instance. Stars.built += 1 assigns to the class,
so it works.
Show the instance store failing.
self.built += 1 reads the class attribute, adds
one, and then tries to store the result on the instance. That
store is the assignment frozen=True refuses.
The type checker rejects self.built += 1 before
the program runs and reports built as read-only on
a frozen instance. The listing carries a
# type: ignore so it can demonstrate the runtime
failure.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
dict
field default, three waysGive
Monthsa second field, adict[str, Month]index written with a= {}default, and read the error@dataclassreports. Fix it withdefault_factory=dict. Then change the factory tolist, and compare what the type checker reports with what the program does.
Defaults
Built Fresh, Not Shared shows @dataclass
rejecting a mutable default and
field(default_factory=...) as the fix. Wrap the
class definition that has the = {} default in
expected(ValueError) to capture the message. Then
write the fixed class and a third class whose factory is
list, and compare the type each factory builds with
the field’s annotation.
# The shape of exercise_7.py
from dataclasses import dataclass, field
from exceptions import expected
@dataclass(frozen=True)
class Month:
name: str
n: int
def make_months() -> list[Month]:
...
@dataclass(frozen=True)
class Fixed:
months: list[Month] = field(default_factory=make_months)
index: dict[str, Month] = field(default_factory=dict)
@dataclass(frozen=True)
class WrongFactory:
months: list[Month] = field(default_factory=make_months)
index: dict[str, Month] = field(default_factory=list) # type: ignorethe = {} version fails at the class definition
with
mutable default <class 'dict'> for field index is not allowed: use default_factory,
the fixed version builds an empty index, and the
list version builds an empty list. With the
# type: ignore removed,
uv run ty check reports
no-matching-overload on the field()
call that takes list.
The listing cuts Month down to name
and n, builds two months in place of twelve, and
puts the new field on three variants (Broken,
Fixed, and WrongFactory) that stand in
for the chapter’s Months.
# exercise_7.py
from dataclasses import dataclass, field
from exceptions import expected
@dataclass(frozen=True)
class Month:
name: str
n: int
def make_months() -> list[Month]:
return [Month("January", 1), Month("February", 2)]
with expected(ValueError):
@dataclass(frozen=True)
class Broken:
months: list[Month] = field(
default_factory=make_months)
index: dict[str, Month] = {}
#: [ValueError] mutable default <class 'dict'> for field
#: index is not allowed: use default_factory
@dataclass(frozen=True)
class Fixed:
months: list[Month] = field(default_factory=make_months)
index: dict[str, Month] = field(default_factory=dict)
@dataclass(frozen=True)
class WrongFactory:
months: list[Month] = field(default_factory=make_months)
index: dict[str, Month] = field(default_factory=list) # type: ignore
print(Fixed().index, WrongFactory().index)
#: {} []Provoke the decorator’s error.
= {} fails at the class definition, before any
instance exists. @dataclass inspects the default as
the decorator runs, finds an unhashable object, and raises a
ValueError naming the fix.
Fix it with a factory. Fixed
passes dict as the factory. Each
Fixed() calls dict() and gets an empty
index of its own.
Give the field the wrong factory.
WrongFactory declares a
dict[str, Month] and builds a list.
@dataclass accepts the class, and
WrongFactory().index is []. If a later
statement reads index["January"], Python raises a
TypeError at that statement. The type checker
compares the type the factory builds with the annotation. It
reports no-matching-overload on the
field() call, before the program runs. The
# type: ignore suppresses that report so the
listing can print the list.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.
stars_float.pybuilds aStarsholding5.5. Add a type test to the check in__post_init__()so thatStars(5.5)raisesTypeFailure.Stars(True)also passes the range check. Explain why anisinstance()test accepts it, and write the test so that it rejectsTrueas well.
The
Annotation and the Check shows Stars(5.5)
passing because Python ignores the annotation at runtime. Add a
type test as the first call to check() in
__post_init__(), before the range comparison. For
True, consider how bool relates to
int, and compare the class of the value with
int instead of using isinstance().
# The shape of exercise_8.py
from dataclasses import dataclass
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
...
def check(condition: bool, subject: str,
reason: str = "") -> None:
...
@dataclass(frozen=True)
class Stars:
number: int
def __post_init__(self) -> None:
...your exercise_8.py raises a
TypeFailure from the type test for
Stars(5.5), Stars(True), and
Stars("five"), and Stars(5) still
builds. Stars("five") must end in a
TypeFailure, not a TypeError from the
range comparison.
The
Annotation and the Check writes the type test as
isinstance(self.number, int) for a type built at a
JSON boundary. If you write the type test that way,
Stars(5.5) and Stars("five") raise a
TypeFailure, but Stars(True) builds
Stars(number=True). The demo loop then stops with
an AssertionError, which expect()
raises when the call it makes returns normally. The solution
compares the class of the value with int, a test
that a bool fails.
# exercise_8.py
from dataclasses import dataclass
from exceptions import expect
@dataclass(eq=False)
class TypeFailure(ValueError):
subject: str
reason: str = ""
def __str__(self) -> str:
return f"{self.subject} {self.reason}".rstrip()
def check(condition: bool, subject: str,
reason: str = "") -> None:
if not condition:
raise TypeFailure(subject, reason)
@dataclass(frozen=True)
class Stars:
number: int
def __post_init__(self) -> None:
check(type(self.number) is int,
f"Stars({self.number!r})", "needs an int")
check(1 <= self.number <= 10,
f"Stars({self.number})")
print(Stars(5))
#: Stars(number=5)
for bad in (5.5, True, "five"):
expect(TypeFailure, Stars, bad) # type: ignore
#: [TypeFailure] Stars(5.5) needs an int
#: [TypeFailure] Stars(True) needs an int
#: [TypeFailure] Stars('five') needs an int
print(issubclass(bool, int), isinstance(True, int))
#: True TrueTest the exact class. bool is a
subclass of int, so
isinstance(True, int) is True and an
isinstance() test accepts True as the
rating 1.
Test the type before the range. Comparing
"five" with 1 raises a
TypeError, so if the range check runs first, a
str ends in that TypeError instead of
a TypeFailure.
Feed values the type checker refuses. The
type checker rejects 5.5 and "five" as
arguments before the program runs. The
# type: ignore silences that report so the listing
can show what the constructor does with each value at
runtime.
The type checker accepts Stars(True), because
bool is a subclass of int to the
checker as well as to isinstance(). In the loop the
three values reach the checker as one union, so its report names
True beside the two values it rejects; a direct
Stars(True) passes. The runtime test is therefore
the one check that rejects True.
Before you move on, name what separates your attempt from this one: a different design, a detail, or an equivalent alternative.