Checkpoint: OOP & Standard Library
Published by Brayan K
A checkpoint is a consolidation stop: you recap the cluster of skills you just learned — abstract base classes, properties, __slots__, scope, custom exceptions, zoneinfo, pickle, and configparser — and prove they fit together by building one small program that uses several at once.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give each boundary one responsibility
Build a small report queue that accepts configuration, creates validated jobs, formats a report and saves a trusted snapshot. Configuration text is not application state, and a restored dictionary is not automatically a valid job. Draw the boundaries before combining the classes: parse settings, validate fields, render accepted jobs, then serialize only the state you mean to retain.
The queue’s contract is deliberately small. A job has a nonempty name and a positive integer unit count. A formatter supplies one line per job. A snapshot stores schema 1 and plain job records. Disabled configuration produces no report. All inputs in this checkpoint are fixed in memory, so you can reproduce every output without a server or the current clock.
The design uses Abstract Base Classes (abc) for a formatter contract, Properties & Descriptors for validation and __slots__ & Memory Optimization for explicit storage names. Those lessons own the mechanisms; here you decide where they belong in one program.
Make invalid state fail during construction and later updates
class JobError(Exception):
pass
class Job:
__slots__ = ("name", "_units")
def __init__(self, name, units):
if type(name) is not str or not name.strip():
raise JobError("name must be nonempty text")
self.name = name.strip()
self.units = units
@property
def units(self):
return self._units
@units.setter
def units(self, value):
if type(value) is not int or value < 1:
raise JobError("units must be a positive integer")
self._units = value
job = Job(" draft ", 2)
print(job.name, job.units)
try:
job.units = 0
except JobError as error:
print(str(error))
print(job.units)
print(hasattr(job, "__dict__"))
# ✅ Expected output:
# draft 2
# units must be a positive integer
# 2
# FalseThe setter validates before updating the backing field, so a rejected change preserves the prior value. The constructor uses the public property and cannot silently admit a unit count the setter would reject later. Slots restrict storage names; they do not perform the range check or stop name from being reassigned. A production design needing name validation on every update would make that field managed too.
class JobError(Exception):
pass
def require_units(value):
if type(value) is not int or value < 1:
raise JobError("units must be a positive integer")
return value
require_units(True)
# ✅ Expected error:
# JobError: units must be a positive integerThe exact-type check deliberately rejects True. That is a domain policy for units, not a claim that bool is unrelated to int in Python. Booleans & Truthiness owns that language relationship.
Translate malformed settings without hiding programming bugs
from configparser import ConfigParser, Error as ConfigError
class SettingsError(Exception):
pass
def read_settings(text):
config = ConfigParser(interpolation=None)
try:
config.read_string(text)
enabled = config.getboolean("report", "enabled")
limit = config.getint("report", "limit")
except (ConfigError, ValueError) as error:
raise SettingsError("invalid report configuration") from error
if not 1 <= limit <= 20:
raise SettingsError("limit must be between 1 and 20")
return enabled, limit
valid = """[report]
enabled = yes
limit = 2
"""
invalid = """[report]
enabled = yes
limit = many
"""
print(read_settings(valid))
try:
read_settings(invalid)
except SettingsError as error:
print(str(error))
print(type(error.__cause__).__name__)
# ✅ Expected output:
# (True, 2)
# invalid report configuration
# ValueErrorThe conversion try block contains only the parser operations whose failures are translated. The range check follows it, so a deliberate domain refusal is not mislabeled as malformed INI. Config Files with configparser owns getters and defaults; Custom Exceptions & Exception Chaining owns the cause relationship.
Keep report formatting replaceable without pretending an interface proves correctness
from abc import ABC, abstractmethod
class Formatter(ABC):
@abstractmethod
def format(self, name, units):
pass
class Compact(Formatter):
def format(self, name, units):
return f"{name}: {units}"
class Verbose(Formatter):
def format(self, name, units):
return f"Job {name} needs {units} units"
def report(rows, formatter):
return [formatter.format(name, units) for name, units in rows]
rows = [("draft", 2), ("review", 1)]
print(report(rows, Compact()))
print(report(rows, Verbose()))
# ✅ Expected output:
# ['draft: 2', 'review: 1']
# ['Job draft needs 2 units', 'Job review needs 1 units']The caller does not branch on formatter type. Both implementations honor the same parameters, and their checked outputs establish their actual behavior. ABC enforcement alone would accept an override with an incompatible signature or an unhelpful body; the concrete examples still need to be run.
Persist data that can be validated and reconstructed
import pickle
records = (("draft", 2), ("review", 1))
payload = pickle.dumps({"schema": 1, "jobs": records}, protocol=4)
snapshot = pickle.loads(payload)
if type(snapshot) is not dict or snapshot.get("schema") != 1:
raise ValueError("unsupported snapshot schema")
print(snapshot["schema"])
print(snapshot["jobs"])
print(type(snapshot["jobs"]).__name__)
# ✅ Expected output:
# 1
# (('draft', 2), ('review', 1))
# tupleThese bytes were produced by this program from known data. Serialization with pickle explains why untrusted pickles must not be loaded at all: a shape check after loads cannot prevent code execution during reconstruction. Plain records also avoid coupling this snapshot directly to the import path of the Job class.
Restoration should call Job(name, units) for every accepted record, applying the same validation as a new request. It should not write directly into _units or assume that a familiar schema number proves every field is valid. Keep the byte-format protocol and the application’s schema version as separate decisions.
Display a known instant without making the report depend on the current clock
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
created = datetime(2020, 7, 1, 12, tzinfo=timezone.utc)
local = created.astimezone(ZoneInfo("Europe/London"))
print(created.isoformat())
print(local.isoformat())
# ✅ Expected output:
# 2020-07-01T12:00:00+00:00
# 2020-07-01T13:00:00+01:00This optional heading example needs a local IANA time-zone database. It converts a known instant; it does not parse an ambiguous user-entered wall time. Time Zones with zoneinfo owns missing/repeated times and recurrence policies. The queue below does not require a clock or zone database.
Complete the formatter boundary before combining the pipeline
Fill the abstract decorator, the concrete return value and the formatter instance. The caller should use the shared method without testing which subclass it received.
from abc import ABC, abstractmethod
class Formatter(ABC):
@___
def format(self, name, units):
pass
class Compact(Formatter):
def format(self, name, units):
return ___
formatter = ___
print(formatter.format("review", 2))
# 👉 replace ___ with abstractmethod
# 👉 replace ___ with f"{name}: {units}"
# 👉 replace ___ with Compact()
# ✅ Expected output:
# review: 2Restore a report queue through its public validation path
Combine the pieces into one program. Read enabled=yes and limit=2 from a report section. Create draft with 2 units and review with 1 unit. Use a slotted Job with the validating units property, and a concrete Compact formatter implementing an abstract Formatter. Save only schema 1 plus tuples of name and units using protocol 4. Reload those locally created bytes, validate the envelope and record shapes, and reconstruct each Job through its constructor. If enabled, print at most limit formatted jobs. Finally create a second trusted snapshot containing bad with 0 units and show that restoration rejects it. Keep a broken payload from replacing the accepted queue.
import pickle
from abc import ABC, abstractmethod
from configparser import ConfigParser
class JobError(Exception):
pass
class Job:
__slots__ = ("name", "_units")
def __init__(self, name, units):
if type(name) is not str or not name.strip():
raise JobError("name must be nonempty text")
self.name = name.strip()
self.units = units
@property
def units(self):
return self._units
@units.setter
def units(self, value):
if type(value) is not int or value < 1:
raise JobError("units must be a positive integer")
self._units = value
class Formatter(ABC):
@abstractmethod
def format(self, job):
pass
class Compact(Formatter):
def format(self, job):
return f"{job.name}: {job.units}"
def restore_trusted(payload):
snapshot = pickle.loads(payload)
if type(snapshot) is not dict or snapshot.get("schema") != 1:
raise JobError("unsupported snapshot schema")
records = snapshot.get("jobs")
if type(records) is not tuple:
raise JobError("jobs must be a tuple")
restored = []
for record in records:
if type(record) is not tuple or len(record) != 2:
raise JobError("invalid job record")
restored.append(Job(*record))
return restored
config = ConfigParser(interpolation=None)
config.read_dict({"report": {"enabled": "yes", "limit": "2"}})
enabled = config.getboolean("report", "enabled")
limit = config.getint("report", "limit")
if not 1 <= limit <= 20:
raise JobError("limit must be between 1 and 20")
jobs = [Job("draft", 2), Job("review", 1)]
snapshot = {"schema": 1, "jobs": tuple((job.name, job.units) for job in jobs)}
payload = pickle.dumps(snapshot, protocol=4)
jobs = restore_trusted(payload)
formatter = Compact()
if enabled:
for job in jobs[:limit]:
print(formatter.format(job))
bad_payload = pickle.dumps({"schema": 1, "jobs": (("bad", 0),)}, protocol=4)
try:
replacement = restore_trusted(bad_payload)
except JobError as error:
print("Rejected:", error)
else:
jobs = replacement
print("Retained:", [job.name for job in jobs])
# ✅ Expected output:
# draft: 2
# review: 1
# Rejected: units must be a positive integer
# Retained: ['draft', 'review']The replacement is assigned only after complete restoration succeeds. The failing record cannot partially overwrite the accepted queue. Error types, constructor validation, formatting and persistence each have a specific job; adding an abstraction never removes the need to check the data that crosses it.
Practice quiz
Why does Job.__init__ assign through self.units rather than directly to _units?
- To make units immutable
- To reuse the same validation for construction and later updates
- To enable pickle automatically
- To eliminate the need for a backing field
Answer: To reuse the same validation for construction and later updates. Both entry points should enforce the same domain rule.
What does this program print? def valid_units(value): return type(value) is int and value > 0 print(valid_units(True), valid_units(2), valid_units(0))
- True True False
- False False False
- True True True
- False True False
Answer: False True False. The chosen policy rejects booleans and nonpositive integers.
Which operation must happen before deciding that unpickling is acceptable?
- Establish that the bytes come from a trusted, untampered source
- Check the returned schema field
- Build a Job from every returned record
- Catch ValueError
Answer: Establish that the bytes come from a trusted, untampered source. Post-load checks cannot undo reconstruction of hostile pickle instructions.
What does this program print? from configparser import ConfigParser c = ConfigParser() c.read_dict({"report": {"enabled": "no", "limit": "2"}}) print(c.getboolean("report", "enabled")) print(type(c.getint("report", "limit")).__name__)
- True str
- False str
- False int
- True int
Answer: False int. Typed getters establish the application value types.
When should a restored replacement queue overwrite the active queue?
- After the first valid record
- Before checking the envelope
- Even if one record fails
- Only after all records have been validated and reconstructed
Answer: Only after all records have been validated and reconstructed. Prepare the complete replacement before changing accepted application state.
What does this program print? class Job: __slots__ = ("units",) job = Job() job.units = 2 job.units = 0 print(job.units)
- 0
- 2
- AttributeError
- ValueError
Answer: 0. Slots alone impose no positive-range validation.
What does the abstract formatter requirement fail to prove by itself?
- That the class has a name
- That a concrete implementation has compatible behavior and parameters
- That Python supports methods
- That a method can return text
Answer: That a concrete implementation has compatible behavior and parameters. The implementation still needs behavioral checking.
What does this program print? import pickle s = {"schema": 1, "jobs": (("A", 2),)} r = pickle.loads(pickle.dumps(s, protocol=4)) print(r["jobs"][0][0]) print(type(r["jobs"]).__name__)
- A list
- 2 tuple
- A tuple
- A bytes
Answer: A tuple. The plain record graph keeps its tuple structure.
Continue this course
- Previous: Config Files with configparser
- Next: Threading & the GIL — Run concurrent I/O with threads and understand why the GIL limits CPU work
- Quick reference: Python cheat sheet