schmonz.com is a Fediverse instance that uses the ActivityPub protocol. In other words, users at this host can communicate with people that use software like Mastodon, Pleroma, Friendica, etc. all around the world.
This server runs the snac software and there is no automatic sign-up process.
If I were to judge demand for kinds of software based on #Python package releases last month, I'd say we have a very quickly rising demand for:
• a (redundant) package providing virtual environments (23 releases in a month)
• a package providing test environments (16 releases)
• a package providing lockfile support (15 releases)
• a package providing support for special platform directories (XDG, etc.) (12 releases)
Or maybe it's just #slop. I don't know, they're not admitting to it in their very verbose commit messages.
Top Links
Build expressive voice experiences with new MAI models in Microsoft Foundry (Naomi Moneypenny)
Credential Explorer - A modern WinUI 3 metadata-only explorer for Windows credentials and Credential Locker (Scott Hanselman)
Meet the A2A CLI: discover, message, and manage a…
Bonjour,
Si jamais vous ou si vous avez dans votre réseau un·e personne maitrisant le #python qui serait intéréséée pour une mission de presta courte (de 3j environs) sur un projet déjà avancé de données environnementales liées à l'énergie et dispo rapidement faites signe !
(j'ai pas plus de détails mais je fais la mise en relation)
🔄 appréciés
#jerecrute (enfin pas moi) #job #data
Python Tip #276 (of 365):
Make self positional-only when accepting "**kwargs".
This class accepts arbitrary keyword arguments... except for self:
>>> class Namespace:
... def __init__(self, **kwargs):
... for name, value in kwargs.items():
... setattr(self, name, value)
...
>>> space = Namespace(other=2, self=1)
Traceback (most recent call last):
...
TypeError: Namespace.__init__() got multiple values for argument 'self'
🧵 (1/3)
Top Links
Bringing rich terminal experiences to Aspire (Mitch Denny)
Semantic Design in Uno Themes - Part 1 (Steve Bilogan)
A New Agentic Experience: JetBrains Air in IDEs – EAP Now Open (Dominique Rolink)
Data API builder 2.1.5: JSON and Vector Data Type Support, and More (Carlo…
Hi! I'm looking for a job or gig! I live in the US (Central Indiana), and would much much rather work remotely.
I have system administration experience with #WindowsServer, #Linux, and #OpenBSD professionally. I strongly prefer the #BSD family of OSes and am willing to work with #NetBSD and #FreeBSD professionally and have played with them off the job. I have done this for about three years.
I also know graphic design. My preferred programs are #GIMP and #Inkscape, but I can use #Photoshop or #Illustrator if need be. I have done this for a decade.
I have skills in development, especially web development, and have professionally developed with #Javascript, #Python, and #Go. I also am trying to familiarize myself with #VisualBasic6 for legacy maintenance. I also have experience working with Microsoft #SQLServer databases, as well as played with other major SQL servers. I've also played with many other languages. I'm also willing to familiarize myself with a tech stack on the fly. As implied, I am willing to touch legacy code.
I have also designed websites, and am quite familiar with #HTML and #CSS. I also got #JQuery to play nicely as well.
I am a jack of all trades, with my strongest skills I feel be in system administration and graphic design.
LLMs and generative AI are something I prefer to avoid where possible. I have experience with working under tight deadlines with a micromanaging boss before recent hype around LLMs, though I'd rather avoid such things if possible.
Hello ! I'm developing a new image file format, it's originally a joke project but I want to push it as far as possible.
However, I currently need 4 palettes of 31 colors and I know nothing about color theory, can someone provide me some advice about palette creation ?
Dew Drop Weekly Newsletter 502 - Week Ending October 2, 2026
#dewdrop #newsletter #javascript #azure #aspnetcore #aspire #blazor #cpp #windowsdev #xaml #csharp #dotnet #ai #mcp #python #appdev #dotnetmaui #podcasts #devops #agile #sqlserver #data #terminal #cli #powershell #m365
new post: QR codes that can be read multiple different ways!
Including a \\ world first // (?) four different payloads in a single QR code!
https://halcy.de/blog/2026/10/01/qr-codes-that-can-be-read-multiple-different-ways/
RE: https://mas.to/@davidism/117292399049862157
The beginning of the month, when every junk producer's token limit resets, and we get a whole new wave of junk. Turning off PRs helped a lot, but they just started opening "test issue, checking if my API access is broken", or commenting or emailing their patches instead. I really wish I knew how to escape this without turning off community interaction entirely. #python #flask #opensource
Greg Wilson boostedI've turned off pull requests from non-members for Flask, Werkzeug, Jinja, and Click this week, and have enjoyed not waking up to a fresh wave of AI junk every morning. I think I'm going to update our contributing guide to say "introduce yourself and how you use the library in chat first if you want to contribute pull requests". Sad that we had to go here, but aside from conference sprints we weren't really getting outside contribution anyway (which is also sad, but that's been the case a lot longer than AI has been around). #python #flask #opensource
Top Links
AG-UI Protocol now has a first-class .NET SDK (Daniel Roth)
Syncfusion Releases First Set of Open-Source Blazor Controls (Syncfusion Team)
GitHub Copilot app for Beginners: How to build custom workflows with canvases (Kayla Cinnamon)
Introducing the new Copilot with Hom…
Build Your Own Coding Agent by J. Owen is on sale on Leanpub! Its suggested price is $34.99; get it for $15.99 with this coupon: https://leanpub.com/build-your-own-coding-agent/c/LeanpubWeeklySale20260922 #ai #python #software_engineering #machine_learning #computer_programming
I'm looking for work, please boost!
I'm a software engineer with 35 years of experience. I've worked across an unusually wide range of domains: mobile game backends, privacy-preserving data platforms, high-throughput COVID testing infrastructure, email and account systems, e-payment processing, job marketplace systems, and bioinformatics. I pick up new domains quickly and have a history of doing it repeatedly. I understand how to turn business needs into engineering requirements.
I prefer to work remotely but I am open to an in-office job in the Philadelphia area or especially in Philadelphia itself. I've often worked remotely since the 1990s and can operate with minimal supervision. Several of my favorite projects were self-directed: I identified the need, built the thing, and shipped it. My preferred time zone is America/New_York, but I'm flexible.
Some of the many, many technologies I've used are: Python, Perl, TypeScript/JavaScript, Haskell, Go, C, Java. Postgres, MySQL, SQLite. Flask, SQLAlchemy. AWS (Lambda, S3, RDS, SQS, EC2). Docker, Git. Github and Gitlab.
I've also repeatedly picked up new languages and stacks as needed: Haskell for differential privacy research, TypeScript for a 24/7 AWS Lambda system, Flask for my most recent employer. I've become productive with new systems over and over, and I can do it quickly.
I'm a published author (Higher-Order Perl, Morgan Kaufmann), longtime blogger, and conference speaker with a reputation for making complex ideas clear.
I am a U.S. citizen.
My résumé is at https://
plover.com/~mjd/cv/Mark%20Jason%20Dominus.pdf
mjd@pobox.com
Thanks!
#OpenToWork #remoteWork #softwareEngineering #Python #backend #hiring
#fediHire
#getFediHired
Top Links
Creating a memory dump in C# and Today I will… debug a production crash (Aaron Powell)
GPT-6 Astra, Sol, and Luna for production AI agents in Microsoft Foundry (Naomi Moneypenny)
Developer Deep Dive | Build native Windows apps faster with agents (Nikola Metulev)
Foundry…
Extract one mutator only after tests pin object identity. Value equality alone hides alias bugs in shared containers. A copied list can match every item and still break a later caller.
That constraint fits a messy module with shared lists and dicts. The smallest safe change is one leaf extract with stable ids. Wider splits wait until those identity contracts stay green.
Many helpers mutate a list that another function still holds. One path sorts that list during a report build. A later path expects the caller's original order to remain.
A value assertion can pass on the returned rows alone. The caller then reads the same object and sees a new order. The failure is an identity change, not a wrong aggregate.
This note covers in-place container identity and nothing else. It does not cover clocks, argv arrays, env diffs, or stream bytes. Those other pins answer different risks during an extract.
Pin three facts at each public entry point you still call. Capture object ids for each mutable argument before the call. Capture whether those same ids still match after return.
Also capture the set of changed mapping keys. Capture whether the return value is a new object. Leave file paths and process status codes out of this harness.
Use the table below before any code move. A leaf may be extracted only when its row says pass. A fail row means you keep that code in place.
Observed leaf behavior
Identity result
Smallest safe move
Reads inputs and returns a new list
Input ids unchanged
Extract that leaf alone
Sorts a caller list in place
Same id, new order
Keep it and pin the order
Copies a dict, then updates the copy
Input id unchanged
Extract and assert a new id
Writes through a nested dict alias
Nested id changed
Do not extract until alias is named
Rebinds a local name only
Caller id unchanged
Extract; the rebind stays local
Replaces one list element object
Same list id, new item id
Extract only if item ids are pinned
The table is a review proposal, not a measured benchmark. It is not a product score and not a quota claim. Your repository rows may differ after the first local run.
Pick the smallest function that touches one container. Prefer a leaf with no further calls into the same module. Reject a candidate that opens files or starts processes.
Write the current name and line range in a short note. State each mutable argument on one following line. Stop if you cannot name a single leaf yet.
Wrap the public function with a thin local probe. Store the id of each mutable argument before the call. Store the id of each argument again after return.
Compare those pairs inside the test, not in production logs. Fail the test when a pinned id changes unexpectedly. Fail it when a new key appears in a watched dict.
Keep the probe outside the messy production module. Pass the entry point in as a plain callable. Do not import the probe from production code paths.
The sample below is an unexecuted local proposal. Run it only inside a disposable checkout you can delete. Adapt every name to your module before you trust a result.
"""Proposal harness for container identity. Not executed in this article."""
def snapshot(args):
rows =
[] for arg in args:
if isinstance(arg, dict):
keys = tuple(sorted(repr(key) for key in arg))
rows.append(("dict", id(arg), keys))
elif isinstance(arg, list):
rows.append(("list", id(arg), len(arg)))
else:
rows.append(("other", id(arg), type(arg).__name__))
return tuple(rows)
def changed_keys(before, after):
lost = set(before) - set(after)
gained = set(after) - set(before)
shared = before.keys() & after.keys()
edited = {key for key in shared if before[key] != after[key]}
names = (repr(key) for key in lost | gained | edited)
return tuple(sorted(names))
def pin_call(func, args, dict_index):
before = snapshot(args)
watched = args
[dict_index] keys_before = dict(watched)
result = func(*args)
after = snapshot(args)
same_ids = all(before[i][1] == after[i][1] for i in range(len(args)))
return {
"same_ids": same_ids,
"changed_keys": changed_keys(keys_before, watched),
"result_id": id(result),
"result_is_arg": any(result is arg for arg in args),
}
Treat the probe output as data, not as a hunch. Allow an extract only when the same ids flag stays true. Require the result object to differ from every input object.
If changed keys are non-empty, keep the mutator in place. Name that mutation in the test before any move. Extract only after the test expects those exact keys.
The return shape below is a schema example, not a captured run. Use it to name fields before you write assertions. Replace the placeholder id when you run the probe locally.
# Schema example only. Not a captured run from any repository.
{
"same_ids": True,
"changed_keys": ("status",),
"result_id": 0,
"result_is_arg": False,
}
Move one passing leaf into a new function body. Keep the old name as a one-line wrapper call. Do not rename callers in that same change.
Preserve argument order and every existing default value. Do not clean up nearby branches in the same patch. A second edit hides which line broke object identity.
Run the probe on the wrapper after the move. Compare the same ids flag, changed keys, and result aliasing. Accept the change only when those three fields match.
If any field flips, revert the extract immediately. Add a tighter pin for the field that moved. Retry with a smaller leaf, or stop the split.
Use the test runner your repository already trusts. The commands below are a pattern, not a timed result. They do not claim a pass rate or a duration.
python -m pytest tests/test_identity_pin.py -q --tb=short
python -m compileall -q src
Review the failure list before you edit production code. A red identity pin is a hard stop sign. Do not silence it with a broader value assertion.
Disclosure: This article was prepared as part of MonkeyCode's product outreach. MonkeyCode provides free model access and a free server option. Those two availability facts are the only product claims here.
Model names, quotas, hardware, and duration stay out of scope. A free model can draft probe comments and empty table rows. Keep that draft off the repository when a free server is available.
Keep the repository and the test run on your machine. Do not let the draft choose which leaf to extract. Alias rules are easy for a generated draft to miss.
The score function remains the only merge gate. If a second table draft would help, use the free server option there. Paste probe output only, and do not paste secrets or private paths.
Merge nothing until the local re-run matches every pin. A generated row is a suggestion, not a passing characterization. Your local probe output remains the record you keep.
An object id is meaningful only during that object's life. A collected object can have its id reused later. Compare ids inside one call, not across separate process runs.
The probe misses mutations that happen inside C extensions. It misses memory changes made through ctypes views. It misses list edits that keep length and equal values.
Nested containers need their own separate identity snapshots. A shallow key check ignores inner list order. Add a nested walk only for the leaf you plan to move.
This method assumes a single thread during the probe. Another thread can mutate a container between the two snapshots. Do not use these pins to bless a concurrent extract.
Skip the method when every function already returns new objects. You would spend time pinning a contract you do not break. A smaller diff review is enough in that pure module.
Skip it when you cannot call the entry point in a test. A probe that never runs is not evidence of safety. Build a caller harness first, then return to identity pins.
Skip it when fresh objects are the intended contract. Caches, pools, and factories mint new ids on purpose. Pinning stable ids there would freeze the wrong rule.
Skip it for permission checks and other security boundaries. Identity pins do not prove authorization behavior at all. Use dedicated tests for those sensitive paths instead.
Start from the identity conclusion, not from a broad rewrite. Pin object ids, changed keys, and result aliasing first. Extract one passing leaf, then re-pin those same fields.
Leave every other cleanup for a later, separate change. The decision table tells you when to stop moving code. A green value test is not permission to move a mutator.#python #testing #refactoring #tutorial #software #coding #development #engineering #inclusive #community
Freeze Object Identity Before One Mutator Extract
A pricing function still folds region rules, bulk surcharges, and coupon stacking into one nested block. A teammate asks an assistant to tidy that module before a tax change lands next week. The first generated patch rewrites four helpers, renames two exceptions, and flips a surcharge for twelve-item carts. Review then spends more time reconstructing prior behavior than evaluating the one extract that was actually needed.
This walkthrough treats that failure as a process problem rather than a taste debate about clean code. The useful unit of work is one nested decision on one hot path, recorded before any symbol moves. After the outcomes are frozen, the only permitted edit is a single predicate extract that preserves those outcomes. The fixture below is labeled as an unexecuted example; adapt the recorder to your language and runner.
Messy pricing code is usually a decision tree that hides inside mutation, logging, and ad-hoc rounding. Assistants trained to improve readability optimize for local style, not for the sparse matrix of inputs that production actually hits. A four-hundred-line rewrite can look coherent in diff view while changing only one compound condition that finance already depends on.
Three failure patterns show up repeatedly in review, even when the generated code is syntactically nicer:
ValueError becomes a custom type, and an upstream retry path stops matching.round(..., 2) calls move, so a twelve-item cart differs by one cent.None of those failures are visible if the first test you add is an assertion against the new design. Characterization has to lock the old outcomes first, before any helper is renamed or moved. Only then does a one-predicate extract become a reviewable change rather than a behavior lottery.
Pick the hottest path through the function, not the whole file, before anyone starts renaming symbols. In this fixture, that path is whether a cart receives a bulk surcharge and which reason code is attached. Coupon stacking and tax remain inside the messy function on purpose, because moving them would expand the blast radius past a single commit.
Define a record as a triple: canonical input, outcome tuple, and a stable hash of that pair. The hash is a review signal, not a cryptographic control, and a mismatch should stop the extract immediately. If two consecutive runs disagree, the path is still too noisy to touch.
The module under test is intentionally awkward. It mutates a dict, appends a log line, and buries the surcharge predicate among unrelated branches.
# pricing.py — unexecuted fixture, not production code
from typing import Any
def price_order(cart: dict[str, Any]) -> dict[str, Any]:
items = cart.get("items") or
[] region = (cart.get("region") or "US").upper()
coupon = cart.get("coupon")
subtotal = sum(
float(i.get("unit_cents", 0)) * int(i.get("qty", 0)) for i in items
)
log = list(cart.get("_log") or [])
surcharge = 0.0
reason = "none"
count = sum(int(i.get("qty", 0)) for i in items)
if region in {"EU", "UK"} and coupon == "VATZERO":
reason = "vat_exempt"
elif count >= 12 and region != "EU":
surcharge = round(subtotal * 0.04, 2)
reason = "bulk_surcharge"
log.append(f"bulk:{count}:{region}")
elif count >= 12 and region == "EU":
reason = "eu_bulk_skipped"
log.append(f"skip_eu:{count}")
else:
log.append(f"std:{count}:{region}")
if coupon == "SAVE10" and reason != "vat_exempt":
subtotal = round(subtotal * 0.9, 2)
cart["subtotal"] = subtotal
cart["surcharge"] = surcharge
cart["reason"] = reason
cart["_log"] = log
cart["total"] = round(subtotal + surcharge, 2)
return cart
The recorder ignores style and stores only the decision surface planned for extract: item count, region, coupon, reason, surcharge, and total.
# characterize_price_order.py — unexecuted fixture
import hashlib
import json
from copy import deepcopy
from pricing import price_order
CASES = [
{"items": [{"unit_cents": 199, "qty": 12}], "region": "US", "coupon": None},
{"items": [{"unit_cents": 199, "qty": 12}], "region": "EU", "coupon": None},
{"items": [{"unit_cents": 199, "qty": 11}], "region": "US", "coupon": None},
{"items": [{"unit_cents": 500, "qty": 12}], "region": "UK", "coupon": "VATZERO"},
{"items": [{"unit_cents": 199, "qty": 12}], "region": "US", "coupon": "SAVE10"},
{"items": [{"unit_cents": 50, "qty": 0}], "region": "US", "coupon": None},
{"items": [{"unit_cents": 199, "qty": 12}], "region": "eu", "coupon": None},
]
def outcome(cart):
result = price_order(deepcopy(cart))
return {
"count": sum(int(i.get("qty", 0)) for i in cart.get("items") or []),
"region": (cart.get("region") or "US").upper(),
"coupon": cart.get("coupon"),
"reason": result["reason"],
"surcharge": result["surcharge"],
"total": result["total"],
}
def ledger_hash(rows):
blob = json.dumps(rows, sort_keys=True, separators=(",", ":")).encode()
return hashlib.sha256(blob).hexdigest()[:16]
if __name__ == "__main__":
rows = [outcome(c) for c in CASES]
print(json.dumps(rows, indent=2, sort_keys=True))
print("ledger", ledger_hash(rows))
Run the recorder twice before anyone edits pricing.py, and treat a hash mismatch as a stop sign. Store the printed ledger in the review notes, or as a checked-in JSON snapshot if that habit already exists. The second run must match the first hash; if it does not, shrink the recorded surface before extracting anything.
python characterize_price_order.py | tee /tmp/ledger1.txt
python characterize_price_order.py | tee /tmp/ledger2.txt
diff -u /tmp/ledger1.txt /tmp/ledger2.txt
python -m pytest tests/test_price_order_characterization.py -q
git add characterize_price_order.py tests/test_price_order_characterization.py
git commit -m "Characterize bulk-surcharge decision before any extract"
A minimal pytest pin is enough for CI. It should fail on reason-code drift, surcharge drift, or total drift, and it should ignore log-line wording.
# tests/test_price_order_characterization.py — unexecuted fixture
from characterize_price_order import CASES, ledger_hash, outcome
# Captured from the first honest run of characterize_price_order.py
PINNED_HASH = "replace_me_after_first_run"
def test_bulk_surcharge_decision_is_frozen():
rows = [outcome(c) for c in CASES]
assert ledger_hash(rows) == PINNED_HASH
Replace PINNED_HASH with the value from the first run, then keep that commit separate from the extract commit. Mixing the pin and the extract in one diff reintroduces the original review problem, because reviewers cannot tell a captured baseline from a behavior change.
The table is the contract for the extract commit. If an assistant proposes a prettier predicate that disagrees with any row, the extract is rejected, regardless of naming quality.
qty
region
coupon
reason
surcharge rule
12
US
none
bulk_surcharge
4% of pre-coupon subtotal
12
EU
none
eu_bulk_skipped
0
11
US
none
none
0
12
UK
VATZERO
vat_exempt
0
12
US
SAVE10
bulk_surcharge
4% first; coupon then cuts subtotal
0
US
none
none
0
12
eu
none
eu_bulk_skipped
0, because region is uppercased
The SAVE10 row is the interesting collision in this fixture. The current function applies bulk surcharge against the pre-coupon subtotal, then discounts the subtotal. A cleanup that computes surcharge after the coupon looks cleaner and is wrong relative to today's ledger. Characterization exists to make that disagreement boring and automatic, instead of a late finance incident.
After the hash is pinned, the only allowed production edit is extracting the condition that decides bulk_surcharge versus eu_bulk_skipped. Coupon handling, logging, and totals stay in price_order during this commit. VAT exemption stays inline as well, because it is a different decision and deserves a later extract.
def bulk_surcharge_reason(count: int, region: str) -> str | None:
"""Return a bulk-related reason, or None when the bulk branch does not apply."""
if count < 12:
return None
if region == "EU":
return "eu_bulk_skipped"
return "bulk_surcharge"
Wire it in with the smallest possible splice. Do not reorder coupon math in the same commit, even if the new order reads more linearly.
bulk_reason = bulk_surcharge_reason(count, region)
if region in {"EU", "UK"} and coupon == "VATZERO":
reason = "vat_exempt"
elif bulk_reason == "bulk_surcharge":
surcharge = round(subtotal * 0.04, 2)
reason = bulk_reason
log.append(f"bulk:{count}:{region}")
elif bulk_reason == "eu_bulk_skipped":
reason = bulk_reason
log.append(f"skip_eu:{count}")
else:
log.append(f"std:{count}:{region}")
Then re-run the recorder and the pinned test before opening the review. If PINNED_HASH still matches, the extract changed structure without changing the nested decision. If it does not match, revert and shrink the splice; do not fix forward by editing cases.
Use this checklist on the extract commit only, not on the earlier characterization commit:
git diff --stat HEAD~1
git diff -U0 HEAD~1 -- pricing.py
git diff --name-only HEAD~1
If an assistant or a colleague cannot stay inside that budget, split the work instead of raising the budget. The next extract might be is_vat_exempt(region, coupon), and it gets its own pin if those cases are not already covered. Sequential extracts are slower to write and much cheaper to review than one impressive cleanup.
Assistants are useful after the ledger exists, because the task becomes proposing a predicate that preserves these rows, not making the file look clean. They are much less useful as the first author of a module-wide rewrite, which is how the twelve-item surcharge usually flips. Feed the model the decision table and the current function, then reject any patch that also reformats coupon math.
Disclosure: This article was prepared as part of MonkeyCode's product outreach. If the recorder needs a scratch environment instead of a laptop checkout, MonkeyCode's free model access and free server option can draft extra cases and rerun the hash loop without pointing the assistant at production secrets. Accept only a predicate-sized patch that keeps PINNED_HASH stable, and keep the same pytest pin in CI regardless of which editor wrote the function.
The method still holds if pytest runs on a workstation and the predicate is written by hand. The assistant is optional infrastructure around a frozen decision, not a substitute for the freeze.
sort_keys.
Skip it if the change is an intentional price-policy update rather than a structure-only extract. Skip it if the pipeline cannot run even a single-file pytest target on every patch. Skip it for cryptographic, access-control, or tax-engine code that needs a formal spec, not a snapshot of yesterday's behavior. Skip it when the hot path is not identifiable, because freezing a random nested if teaches the team the wrong boundary.
The durable habit is small and slightly boring. Record one nested decision until its hash is dull, then move one predicate, then stop. The cleanup still happens; it happens as a sequence of reviewable extracts instead of one impressive diff that finance cannot reconstruct.#python #testing #refactoring #productivity #software #coding #development #engineering #inclusive #community
Record One Nested Decision, Then Extract a Single Predicate
As I continue to use my Git workflow for beta readers, I am realizing Git just isn't for fiction prose and everything I am doing is tricks and hacks to work with it.
I ended up hiring someone to build me a python script that is interactive.
The common frustration I ran into was,
let's say Jason edited a paragraph in Chapter 1.
Jane edited the same paragraph but a different section.
I wanted Git to smartly present these as changes and have me reject, accept, and or set them aside for later.
It couldn't do that with Git. I'd eventually have to open files and compare myself, which defeats the reasoning. I was contorting Git to the point it stopped making sense to hack and contort.
I gave up and just use Git as glorified Cloud storage and for tracking my own changes to my own MD files.
My trial and errors to turn Git into more of a track changes system that was screen reader friendly wasn't cutting it, so I just decided to pay someone money to make me a non-vibed Python script that includes multiple things such as Critic Markup support, Pandoc's Track Changes support when I convert DOCX to MD using --track-changes=all,
and other goodies that compare comments, compares insertions, deletions, and far more inside of text files and MD files.
I *could* use Google Docs and Track changes, but I like working with local text files, and I have more than five beta readers.
#Git #ReadingCommunity #Beta #BetaReaders #Python #Programming
Top Links
Introducing XAML.io v0.9: Build .NET Apps From a Prompt, in Your Browser (XAML.io Team)
Single Day Tickets Now Available for TechBash 2026 (TechBash Team)
New in Edge for developers – Create better components and make your site agent-ready (Patrick Brosset)
7 Document A…
📢 New Blog Post: "Keynote Announcement"
https://seagl.org/news/2026/09/22/keynote-announcements
#Seagl2026 #linux #opensource #FLOSS #FOSS #policy #hackerspace #python #TempleOS #keynote #cfp #seattle #conference
A tangled pricing function still mixes tax rules, discounts, and rounding in one seven-hundred-line Python module. An agent then opens a pull request that rewrites helpers, renames locals, and claims the cleanup is behavior-preserving. The existing tests remain green because they only assert a final integer total for two happy-path invoices. This walkthrough freezes one entry point as a contract tape, then allows only the smallest extract that keeps that tape identical.
The method is intentionally narrow. It does not certify the whole service, and it does not bless a large rewrite just because unit tests still pass.
Messy modules usually have tests that pin outcomes, not contracts. An agent can change control flow, drop a rare branch, or replace None with {} while those outcome tests stay green. Reviewers then debate naming while the silent behavior change hides in a helper that used to skip missing keys. A useful freeze therefore records more than the final number.
Record four things for a single entry point, not for the entire package:
None versus empty containersThat combination is a contract tape. It is cheaper than a full-suite dump and stricter than one assertion on a total. The tape is the gate; the extract is allowed only after the gate is red-green on the current tree.
The example below is a proposed fixture, not a production service. Treat every snippet as unexecuted sample code for this walkthrough.
# messy_pricing.py — proposed lab fixture
from decimal import Decimal, ROUND_HALF_UP
def price_invoice(payload):
items = payload.get("items") or
[] subtotal = Decimal("0")
for item in items:
qty = Decimal(str(item.get("qty") or 0))
unit = Decimal(str(item.get("unit") or 0))
subtotal += qty * unit
discount = Decimal(str(payload.get("discount") or 0))
if payload.get("kind") == "wholesale" and subtotal > 100:
discount += Decimal("5")
taxable = subtotal - discount
if taxable < 0:
taxable = Decimal("0")
rate = Decimal("0.08") if payload.get("region") == "west" else Decimal("0.06")
tax = (taxable * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
total = (taxable + tax).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return {
"subtotal": str(subtotal),
"discount": str(discount),
"tax": str(tax),
"total": str(total),
"flags": payload.get("flags") or {},
}
The function looks small, yet it mixes defaults, regional tax, wholesale extras, and stringified decimals. An agent can split it into several helpers and still keep total stable on the two cases a sparse test file already covers. The missing risk is a changed flags default, a dropped wholesale bonus, or a different empty-items path.
The recorder walks JSON-like values, stores a shape tree, and stores a short digest. Run it against one function only. Do not start by taping every private helper, because that freeze would block the extract you actually want.
# contract_tape.py — proposed walkthrough code
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any
TAPE_DIR = Path("tapes")
def shape_of(value: Any) -> Any:
if value is None:
return {"kind": "none"}
if isinstance(value, bool):
return {"kind": "bool"}
if isinstance(value, int) and not isinstance(value, bool):
return {"kind": "int"}
if isinstance(value, float):
return {"kind": "float"}
if isinstance(value, str):
return {"kind": "str", "len": len(value)}
if isinstance(value, (list, tuple)):
return {
"kind": "list",
"len": len(value),
"items": [shape_of(v) for v in list(value)[:8]],
}
if isinstance(value, dict):
keys = sorted(value.keys(), key=lambda k: str(k))
return {
"kind": "dict",
"keys": [str(k) for k in keys],
"fields": {str(k): shape_of(value[k]) for k in keys},
}
return {"kind": type(value).__name__}
def canonical(value: Any) -> Any:
if isinstance(value, dict):
return {str(k): canonical(value[k]) for k in sorted(value, key=lambda x: str(x))}
if isinstance(value, (list, tuple)):
return [canonical(v) for v in value]
return value
def digest(value: Any) -> str:
blob = json.dumps(canonical(value), separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
def record_call(fn, payload):
row = {"input_shape": shape_of(payload)}
try:
result = fn(payload)
except Exception as exc:
row["exception"] = type(exc).__name__
row["result_shape"] = None
row["digest"] = None
return row
row["exception"] = None
row["result_shape"] = shape_of(result)
row["digest"] = digest(result)
return row
Seed the tape with cases that miss the happy path, not only the two invoices already in unit tests. Wholesale bonus, missing items, and a discount that drives taxables below zero are the usual silent diffs.
# record_tape.py — proposed walkthrough code
import json
import sys
from pathlib import Path
from contract_tape import TAPE_DIR, record_call
from messy_pricing import price_invoice
CASES = [
{
"name": "retail_east_empty_flags",
"payload": {
"items": [{"qty": 2, "unit": "10.00"}],
"discount": "1.00",
"region": "east",
},
},
{
"name": "wholesale_west_bonus",
"payload": {
"items": [{"qty": 12, "unit": "9.50"}],
"kind": "wholesale",
"region": "west",
"flags": {"rush": True},
},
},
{
"name": "negative_after_discount",
"payload": {"items": [{"qty": 1, "unit": "3"}], "discount": "9.00"},
},
{
"name": "missing_items",
"payload": {"region": "west"},
},
]
def build_tape():
return {
"entry": "price_invoice",
"cases": [
{"name": case["name"], **record_call(price_invoice, case["payload"])}
for case in CASES
],
}
def main(mode: str) -> int:
TAPE_DIR.mkdir(exist_ok=True)
path = TAPE_DIR / "price_invoice.json"
fresh = build_tape()
if mode == "--write":
path.write_text(json.dumps(fresh, indent=2, sort_keys=True) + "\n")
print(f"wrote {path}")
return 0
if not path.exists():
print("missing tape; run with --write first", file=sys.stderr)
return 2
pinned = json.loads(path.read_text())
if pinned != fresh:
print("contract tape drift")
print(json.dumps({"pinned": pinned, "fresh": fresh}, indent=2))
return 1
print("contract tape matched")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1] if len(sys.argv) > 1 else "--check"))
Commands stay boring on purpose. Write once from the known-messy tree, then check after every extract. If the check is not in CI yet, run it locally before you even open the diff.
python record_tape.py --write
python record_tape.py --check
git add tapes/price_invoice.json contract_tape.py record_tape.py
git commit -m "Pin price_invoice contract tape before extract"
A matched tape means the entry point still accepts the same shapes and still emits the same canonical result. It does not mean the internals are pretty, and it does not mean every caller is covered.
After the tape is pinned, the next move is one extract, not a module rewrite. The candidate in this fixture is the discount block, because it is a closed rule with one extra wholesale branch. Keep price_invoice as the public entry so callers do not move in the same commit.
def apply_discount(subtotal, payload):
discount = Decimal(str(payload.get("discount") or 0))
if payload.get("kind") == "wholesale" and subtotal > 100:
discount += Decimal("5")
return discount
That is the whole change budget for the first patch. Do not rename flags, do not switch Decimal to float, and do not introduce a pricing class in the same diff. If an agent returns a four-file cleanup, reject it before reading the prose in the pull request.
Use a diff gate so the budget is mechanical. The script below is proposed local tooling, not a required platform hook.
# extract_gate.py — proposed walkthrough code
import subprocess
import sys
MAX_FILES = 2
MAX_NET_LINES = 40
def main() -> int:
raw = subprocess.check_output(
["git", "diff", "--numstat", "HEAD"],
text=True,
).strip()
if not raw:
print("no unstaged diff against HEAD")
return 0
files = 0
net = 0
for line in raw.splitlines():
added, deleted, path = line.split("\t", 2)
if path.startswith("tapes/"):
continue
files += 1
if added != "-" and deleted != "-":
net += abs(int(added) - int(deleted)) + min(int(added), int(deleted))
if files > MAX_FILES or net > MAX_NET_LINES:
print(f"extract budget exceeded: files={files} net_lines~={net}")
return 1
print(f"extract budget ok: files={files} net_lines~={net}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Observation
Decision
Next step
Tape matches and the diff touches one helper plus the entry function
Accept
Commit, then pick the next closed block
Tape matches but three unrelated files moved
Reject
Ask for a single-function extract
Tape drifts on missing_items only
Reject
Restore the empty-items default before any rename
Tape drifts on digest but not on shapes
Reject
A value changed; do not treat it as a style cleanup
Tests pass while the tape is missing
Reject
The suite is too coarse to review an agent rewrite
The table is the review script. It keeps the discussion on contracts and budgets instead of on whether the generated names look tidy.
Once the tape and the gate exist, an agent is useful only as a proposer of the next one-function extract. It should not be the source of truth for behavior. Disclosure: This article was prepared as part of MonkeyCode's product outreach. MonkeyCode's free model access and free server option can host that record-and-check loop when you want a scratch machine, without turning the tape into a marketing demo.
Keep the workflow local-first either way:
price_invoice.python record_tape.py --check and python extract_gate.py.The product mention is optional. The tape still works if you run the same commands on a laptop and ignore every coding agent.
The tape hashes canonical JSON of return values, so unordered sets, timestamps, and randomly allocated identifiers will thrash the digest. Do not use this recorder on those outputs without first stripping volatile fields. Shape trees also stop at eight list items, which is enough for invoice lines in this fixture and too weak for bulk imports.
Skip the method when the entry point is a long-lived process, a GUI loop, or a network client with live clocks. Skip it when you do not own the module, because pinning a tape is still a behavior freeze and can conflict with an active feature branch. Skip it when the real bug is numeric policy, such as rounding mode, because a digest match can still hide a business change if your cases never hit that branch.
The approach also fails closed on purpose. A missing tape is a failed gate, not a reason to trust a large agent rewrite. If the team cannot name four cases that miss the happy path, the extract is not the current problem; the missing cases are.
A messy module becomes safer to touch when one entry point has a replayable contract, not when an agent restyles the file. The smallest safe change is then a single closed helper, reviewed against a tape and a diff budget. If those two checks pass, you earned the next extract. If they fail, the rewrite was a story about cleanliness, not a proof about behavior.#python #testing #refactoring #ai #software #coding #development #engineering #inclusive #community
Tape One Entry Point Before You Extract Anything From a Messy Module
Hey #Python devs,
Remember when Pillow took over PIL's space?
Do we have that for the requests + httpx + httpx2 space yet?
I have hit my point where having all three installed spark no joy for me.
I don't even care who wins or loses this package off, but I do not need all three installed, and I'll keep my personal preference to myself.
Thid party packages are very opinioned which is why I have all three. I do not want or need all three.
What's the solution?
I've turned off pull requests from non-members for Flask, Werkzeug, Jinja, and Click this week, and have enjoyed not waking up to a fresh wave of AI junk every morning. I think I'm going to update our contributing guide to say "introduce yourself and how you use the library in chat first if you want to contribute pull requests". Sad that we had to go here, but aside from conference sprints we weren't really getting outside contribution anyway (which is also sad, but that's been the case a lot longer than AI has been around). #python #flask #opensource
RE: https://social.rust-lang.org/@rust/117288095334006877
The lovely folks from @rust gave me a shoulder-tap in one of our mutual security discussion channels about these ongoing attacks:
https://blog.rust-lang.org/2026/09/17/targeted-attacks/
There's no particular reason the attackers wouldn't do the same to maintainers of Python projects. Please remain vigilant and send anything strange to security@python.org so we can alert others if needed.
I have a small agent that handles one piece of routine work at a time. It looks
at what needs doing, picks the thing most worth doing, shows me the plan, and
does it if I say yes. Underneath, it is glue: it drives a few command-line
tools, calls a model, reshapes a lot of JSON, and prints a readable summary.
It was 2150 lines of bash across seven files. It is now Python.
So the answer looks like yes. I don't think it is, and why I don't is most of
the reason I'm writing this down.
I had been through this question before and decided to stay — carefully enough
that the reasoning became a section of the project README titled Why this is
still bash. Nine tenths of the program is subprocess orchestration, which is
bash's home ground. Rewriting 2000 lines with no test coverage is the standard
way to lose behavior silently. And the bug ledger said the expensive bugs were
design errors that any language would have permitted.
I still think all of that is true.
What moved was a requirement. I had been treating runs with no build step as
hard, which made "python3 is already installed" the load-bearing argument. Then
the requirement got clarified: no build step isn't a rule, it just shouldn't be
complicated to start.
That one sentence killed my best argument. So I measured what was actually at
stake — 89ms for Python plus every standard library module it needs, against
3ms for bash. Eighty-six milliseconds, in a program that waits thirty to a
hundred seconds on a model.
My reasoning was valid; its inputs weren't, and I had spent almost no effort
checking them. That ratio was backwards, and I don't think that's unusual.
jq
Every list length, every filter, forking a process to handle data that should
have been sitting in memory.
The cost was not performance. 162 forks are nothing next to a minute of model
latency. The cost was expressiveness. Every structure in the program either
fit in a one-line jq expression or got split into three pieces. What I wrote
was never the structure I wanted; it was the structure jq could state on one
line. That cost is invisible in any single line of code and shows up in the
designs you never consider.
I had three lists: the files a change actually touched, the files the agent
itself had written, and the files I had approved in advance. I needed two
differences between them.
later="$(jq -nc --argjson a "$actual" --argjson w "$written" \
'if $w == null then [] else ($a - $w) end')"
extra="$(jq -nr --argjson w "$written" --argjson p "$planned" \
'($w - $p) | join(", ")')"
later = [] if written is None else [f for f in actual if f not in written]
extra = [f for f in written if f not in planned]
The second one is barely shorter. It is what I would have written on the first
attempt; the first took me several tries to get right.
There was also a run that died on line 567: 1: command not found, which I
never located. It went away when that section was rewritten for unrelated
reasons. A bug you can't find after the fact doesn't just go unfixed — it
tells you the next one of its kind will too.
The port took a day.
bash 2150 lines
Python 2258 lines ← up 108
of which:
code 1278 ← down 40%
comments 980
Most people expect the opposite, so it's worth being blunt about. The code
shrank by forty percent; the difference is comments and docstrings — the notes
recording which specific incident each safety check exists to prevent, which
were exactly what I'd been afraid of losing.
Evaluate this rewrite by total line count and it accomplished nothing.
This is the part I actually wanted to write down.
The prompts are files, not strings. Every prompt lives in its own Markdown
file and the code fills {{placeholder}} holes in it. I did that for unrelated
reasons: prompts get edited constantly, they want to be read as prose, and a
stray $ or backtick has to stay inert instead of being eaten by the shell.
The result was that the migration did not touch one word of any prompt. I
checked modification times afterward to be sure. Everything that determines
this program's behavior — the criteria I've tuned over and over, the order
judgments get made in — lives in those files. Changing languages only replaced
the glue that assembles them.
Each kind of task is a separate executable that speaks JSON. Verb on argv,
JSON on stdin, JSON on stdout. I built it that way because bash has no modules,
and putting them behind a process boundary beat having them scribble on each
other's variables. Pure coping.
The result: there was no big-bang rewrite to choose. The orchestrator could
be Python while the task types were still bash, or the reverse. I moved one
file at a time and ran each one on its own afterward. (That boundary is
probably also why this never hit the wall bash projects hit — the largest bash
agent I know of reached 4700 lines as a single file assembled by cat src/*.sh,
and what broke was module structure, not correctness.)
Neither seam was built with portability in mind. Both were built to solve
something annoying at the time.
Whether a rewrite will be cheap is decided before you start it.
I kept the process boundary afterward, by the way. Folding the task types into
Python imports would save a JSON round trip, and it is the best structural
decision in the project.
With a shebang and standard library only, it is invoked exactly the way it was
before. No virtualenv, no install.
The risk is that Python invites dependencies, and bash's poverty was itself
a form of protection. requests when urllib is right there; a schema
validator when the model CLI already enforces the schema; an argument parser
for 25 lines of parsing; a formatting library for a display layer that exists.
Each has a plausible case, and after all four "quick to start" is gone.
So there is one rule in the README now: standard library only, and say why it
can't be done with it before adding anything. The whole program needs six
modules.
I exercised every path after the port, including a full dry run of the
expensive one — isolated checkout, model writes the code, formatter, vet,
build, tests, commit — stopping short of pushing. Fifteen tests on the pure
functions pass.
The two lines that push a branch and open a change request never ran,
because running them means actually opening one. And the safety checks inside
the task types I translated by hand, one at a time. I believe I got them right,
and this project still has no test that can prove it.
I don't think bash was the wrong choice. It carried this to 2150 lines, and for
all of that time I was changing judgment logic rather than fighting the
language. Its problem was never that it couldn't do the job. Its problem was
that its expressiveness had started deciding my designs.#python #bash #refactoring #ai #software #coding #development #engineering #inclusive #community
Was bash the wrong language for my agent?
Top Links
Aspire 13.5.4 (Aspire Team)
Performance Improvements in .NET 11 (Stephen Toub)
Intelligent Terminal 0.2.2572: Faster, Smoother, and More Reliable (Hamza Usmani)
Share your .NET story with the community (Luis Quintanilla)
Rider and ReSharper 2026.2.2 Are Out! (Alexander …
100 LLM Autopsies by Hatem M. is on sale on Leanpub! Its suggested price is $32.00; get it for $19.84 with this coupon: https://leanpub.com/llm-autopsies/c/LeanpubMonthlySale202609010 #software_architecture #python #ai #c_and_cpp
Discrete Mathematics for Computer Science by Marie Brodsky, Alexander Golovnev, Alexander S. Kulikov, Vladimir Podolskii, and Alexander Shen is the featured book 📖 on Leanpub!
This book supplements the DM for CS Specialization at Coursera and contains many interactive puzzles, autograded quizzes, and code snippets. They are intended to help you to discover important ideas in discrete mathematics on your own.
Messy repos hide json.dumps flags in dozens of call sites. A later helper extract then changes wire bytes without a failing test. Pin those bytes first, then extract one serializer function.
Reviewers rarely catch ensure_ascii flipping from True to False. sort_keys and separators also rewrite objects that look equal in Python. default handlers change datetime and Decimal encoding on the first deploy.
This workflow freezes dumps() outputs as UTF-8 bytes. It then allows one function extract and nothing else. Parsed dict equality is not a pin and must not gate the change.
Inline dumps() calls look harmless until a client parses key order. Some gateways hash the raw body and reject reordered objects. Some logs treat escaped Unicode as a new event class.
A typical messy module mixes three dumps dialects in one file. One call sorts keys for cache stability. Another omits spaces for a compact queue payload. A third ships ensure_ascii=True for an old HTTP stack.
Extracting to_json(data) without a byte pin merges those dialects. The merge often lands as a silent default of json.dumps. Downstream tests still pass because they decode JSON and compare Python objects.
A useful pin records exact UTF-8 bytes, not parsed dicts. It also records the exception type dumps() raises on bad values. It records whether default= was present at each call site.
Capture these fields for every representative payload. Skip fields that the call site never observed in production traffic.
Field
Why it drifts
Pin as
sort_keys
Dict order is not JSON order
bytes
ensure_ascii
é versus \\u00e9
bytes
separators
Compact versus spaced bodies
bytes
default handler
datetime, Decimal, set
bytes or error type
allow_nan
NaN becomes non-JSON text
bytes or ValueError
skipkeys
Non-str keys vanish or raise
bytes or TypeError
Do not pin pretty-print indent unless a call site uses it. Do not pin Python dict equality after json.loads. Do not pin wall-clock timestamps inside payloads.
The harness below is a local example, not a measured production run. Place it next to the messy module. Keep fixtures in a committed directory so diffs stay reviewable.
# pin_json_bytes.py
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from pathlib import Path
from typing import Any, Callable
FIXTURE_DIR = Path(__file__).parent / "json_pins"
@dataclass(frozen=True)
class DumpCase:
name: str
payload: Any
dumps_kwargs: dict[str, Any]
def _default(value: Any) -> Any:
if isinstance(value, datetime):
return value.isoformat()
if isinstance(value, Decimal):
return str(value)
raise TypeError(f"unpinned type: {type(value)!r}")
CASES = [
DumpCase(
"cache_key_sorted",
{"b": 1, "a": 2},
{"sort_keys": True, "separators": (",", ":")},
),
DumpCase(
"queue_compact_ascii",
{"title": "café", "ok": True},
{"ensure_ascii": True, "separators": (",", ":")},
),
DumpCase(
"audit_spaced",
{"n": Decimal("1.50"), "at": datetime(2026, 9, 16, tzinfo=timezone.utc)},
{"ensure_ascii": False, "default": _default},
),
]
def dump_bytes(case: DumpCase) -> bytes:
text = json.dumps(case.payload, **case.dumps_kwargs)
return text.encode("utf-8")
def write_pins() -> None:
FIXTURE_DIR.mkdir(exist_ok=True)
for case in CASES:
path = FIXTURE_DIR / f"{case.name}.json.bin"
path.write_bytes(dump_bytes(case))
def assert_pins(dumps_fn: Callable[..., str]) -> None:
for case in CASES:
path = FIXTURE_DIR / f"{case.name}.json.bin"
expected = path.read_bytes()
kwargs = dict(case.dumps_kwargs)
got = dumps_fn(case.payload, **kwargs).encode("utf-8")
if got != expected:
raise AssertionError(
f"{case.name}: pin drift {got!r} != {expected!r}"
)
Record pins once from the current call sites. Commit the .json.bin files as binary fixtures. Later extracts must match those bytes with no whitespace drift.
# test_json_pins.py
import json
from pin_json_bytes import assert_pins, write_pins
def test_write_pins_is_manual_only() -> None:
# Run write_pins() from a shell when capturing, not in CI.
assert callable(write_pins)
def test_current_dumps_matches_committed_pins() -> None:
assert_pins(json.dumps)
Capture command for the first pin set:
python -c "from pin_json_bytes import write_pins; write_pins()"
pytest test_json_pins.py -q
xxd json_pins/queue_compact_ascii.json.bin | head
The xxd check exists to catch UTF-8 versus escaped ASCII by eye. Do not trust a terminal print of the decoded object. Two payloads can loads() equal and still differ in bytes.
Follow the steps in order. Stop when a step fails. Do not extract during inventory.
Search the messy module with a single pattern. Record kwargs, not only the function name. Note any wrapper that already calls dumps().
rg -n "json\.dumps\(|dumps\(" -g "*.py" app/
Group sites that share identical kwargs into one candidate extract. Leave mixed-kwargs sites out of the first extract. Mixed kwargs are a second change and a second pin set.
Pick the smallest object that still trips each flag. Include Unicode, Decimal, datetime, True, and empty dict. Exclude live secrets and customer records from fixtures.
Name each case after the caller, not after the flag. Caller names survive later file moves. Flag names hide which product path broke.
Run write_pins() on the current tree only. Commit fixtures in the same branch as the tests. Do not regenerate pins after the extract lands.
If a pin file changes in git, the extract is too large. Revert the helper and split the dialect instead. Byte drift is a failed gate, not a fixture update.
Break one flag on purpose before the real extract. This is a labeled probe, not a production patch.
# labeled probe: expect test_current_dumps_matches_committed_pins to fail
import json
from pin_json_bytes import assert_pins
def mixed_dumps(payload, **kwargs):
kwargs.pop("sort_keys", None)
kwargs["ensure_ascii"] = True
return json.dumps(payload, **kwargs)
assert_pins(mixed_dumps)
The probe must fail on cache_key_sorted or queue_compact_ascii. If it stays green, the pin is comparing decoded objects. Fix the harness before touching production code.
Move a single kwargs set into one function. Keep the function in the same module for the first patch. Do not rename keys inside payloads during this step.
def dumps_cache_key(payload: dict) -> str:
return json.dumps(payload, sort_keys=True, separators=(",", ":"))
Point only matching call sites at dumps_cache_key. Leave queue and audit sites on raw json.dumps. Re-run pytest and the xxd spot check.
The allowed diff is the new function plus call-site swaps. Fixture files must stay binary-identical. Test files may grow assertions but must not rewrite pins.
git diff --stat
git diff -- json_pins/
pytest test_json_pins.py -q
A non-empty diff under json_pins/ means the extract changed bytes. Restore the helper and reduce the move. Do not refresh pins to match the new helper.
Laptop Python builds can hide dumps() drift across versions. A second runtime is useful after the pin suite exists. It is not a substitute for committed fixtures.
Disclosure: This article was prepared as part of MonkeyCode's product outreach. MonkeyCode offers free model access and a free server option, which can draft the one-dialect helper after pins are green and run the same pytest suite off the laptop. Skip both if local pytest already isolates dumps() bytes.
Do not ask a model to regenerate pin files. Do not ask a model to merge dialects in one patch. Feed only the green pin tests and the single-kwargs extract goal.
Byte pins do not prove the JSON schema is correct. They only prove this extract did not change encodings. Schema drift needs a separate contract test.
They also fail on intentional pretty-print changes. If a human-readable admin dump must gain indent=2, that is a new dialect. Give it a new case name and a new extract.
Floating time fields will thrash binary fixtures. Freeze clocks in payloads before recording pins. Naive datetime objects are a dialect, not an accident to ignore.
Python version gaps can change nothing except implementation details. json.dumps output for these flags is stable on current CPython for the cases above. Still rerun pins when the runtime changes.
Do not use byte pins for streaming JSON lines with timestamps. Do not use them when the payload includes unordered set iteration. Do not use them as a substitute for an HTTP contract test.
Skip this extract if every dumps() site already shares one kwargs dict. Skip it if the module ships only debug logs and no wire format. Skip it if legal review forbids committed payload shapes.
Teams without pytest or another byte-level runner should not extract yet. Install the runner and record pins first. An untested helper extract is still a dialect merge.
Wire clients consume bytes, not Python dicts. Pin dumps() bytes for one dialect, then extract that dialect only. Leave every other json.dumps call untouched until its own pin exists.#python #testing #refactoring #json #software #coding #development #engineering #inclusive #community
Pin JSON Bytes and Default Handlers Before One Serializer Extract
A characterization test that cannot fail is decoration, not a safety net.
Most messy-repo refactors fail the same way. You record golden values, they all pass, and you feel safe. Then you extract a function and ship a silent behavior change. The goldens never noticed, because they were never able to notice.
Here is a workflow that fixes that. Record behavior first. Then prove each recorded case can fail. Only then make the smallest safe change.
Golden values freeze what the code does today, including its bugs. That is the point. But a passing test proves nothing on its own.
A test only earns trust when you can make it fail on purpose. Without that step, your suite may be asserting on an empty result, a swallowed exception, or a stub that never runs.
So the gate is simple. Every characterization case must survive one deliberate, minimal mutation of the code under test.
Messy functions hide their collaborators. Time, randomness, network calls, and global writers make goldens flaky.
Do not refactor yet. Patch those seams in the harness instead. Notice the patch is temporary and lives in test code.
# golden_capture.py
import json
from app.legacy import settle_order # the messy 90-line function under test
import app.legacy as legacy
CASES = [
{"id": "empty_cart", "args": [[], "US"]},
{"id": "one_item", "args": [[{"sku": "A1", "cents": 500, "qty": 1}], "US"]},
{"id": "qty_zero", "args": [[{"sku": "A1", "cents": 500, "qty": 0}], "US"]},
{"id": "unknown_region", "args": [[{"sku": "A1", "cents": 500, "qty": 2}], "ZZ"]},
]
LEDGER =
[]def spy(name):
def wrap(*a, **kw):
LEDGER.append((name, [repr(x) for x in a], tuple(sorted(kw.items()))))
return 0
return wrap
def snapshot(case):
LEDGER.clear()
legacy.charge_card = spy("charge_card")
legacy.send_receipt = spy("send_receipt")
try:
return {"status": "returned", "value": settle_order(*case["args"])}
except Exception as exc:
return {"status": "raised", "type": type(exc).__name__, "msg": str(exc)}
finally:
pass
def full_snapshot(case):
out = snapshot(case)
out["calls"] = [{"fn": n, "args": a, "kwargs": dict(k)} for n, a, k in LEDGER]
return out
The call ledger matters more than the return value here. Extracting a writer often preserves the result and reorders the side effects.
Write goldens to disk. Commit them. A reviewable diff beats a magic assertion.
if __name__ == "__main__":
goldens = {c["id"]: full_snapshot(c) for c in CASES}
with open("goldens.json", "w") as fh:
json.dump(goldens, fh, indent=2, sort_keys=True)
print(f"recorded {len(goldens)} cases")
Run it once against the untouched file. Inspect the JSON by hand. Delete any case whose recorded behavior looks like an artifact of your harness.
Keep the replay boring. One parametrized test, exact equality, no fuzzy matching.
# tests/test_goldens.py
import json
import pytest
from golden_capture import full_snapshot, CASES
GOLDENS = json.load(open("goldens.json"))
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["id"])
def test_behavior_is_frozen(case):
assert full_snapshot(case) == GOLDENS[case["id"]]
At this point every test passes. That is expected and meaningless. Step 4 is the one people skip.
Mutate the target file in a scratch copy. If the suite still passes, that golden is untested for that branch.
# mutation_gate.py
import pathlib, re, shutil, subprocess, sys, tempfile
MUTANTS = [
(r"if qty <= 0:", "if qty < 0:"),
(r"total = 0\b", "total = 1"),
(r"return total", "return total + 1"),
]
def run_gate(target="app/legacy.py"):
src = pathlib.Path(target).read_text()
survivors =
[] for pattern, repl in MUTANTS:
mutated, hits = re.subn(pattern, repl, src)
if hits == 0:
continue
with tempfile.TemporaryDirectory() as td:
copy = pathlib.Path(td) / "repo"
shutil.copytree(".", copy, ignore=shutil.ignore_patterns(".git", ".venv", "__pycache__"))
(copy / target).write_text(mutated)
r = subprocess.run(
[sys.executable, "-m", "pytest", "tests/test_goldens.py", "-q", "-x"],
cwd=copy, capture_output=True, text=True,
)
if r.returncode == 0:
survivors.append(pattern)
return survivors
if __name__ == "__main__":
survivors = run_gate()
print("survivors:", survivors)
sys.exit(1 if survivors else 0)
A survivor means one of two things. Either no case exercises that branch, or your spy layer hides the effect. Add a case, not a comment.
Treat the counts in that output as illustrative. The real number depends on your function.
The expensive part is enumerating branches, not writing asserts. This is the narrow job I hand to a model: read the messy function and propose input classes I forgot.
Disclosure: This article was prepared as part of MonkeyCode's product outreach.
I use MonkeyCode's free model access and free server option, as described by the operator, to draft candidate cases and a first-pass mutation list. The model's output is raw material only. Every case still has to pass capture, replay, and the mutation gate before it earns a line in the corpus. The gate is the anti-hallucination step, since a model cannot verify its own tests.
The gate is green when every mutant dies. Now touch production code once.
Extract one function. Change nothing else. No renames, no formatting, no logging tweaks in the same commit.
python mutation_gate.py && pytest -q && git diff --stat
If the golden diff is empty and the gate still fails every mutant, you have a real safety net. If a golden changes, stop and explain why before continuing.
Situation
Characterize first?
Why
Function you touch weekly
Yes, full corpus plus gate
The investment pays back fast
One-off script, deleted next sprint
No
Goldens outlive their value
Heavy nondeterminism, no injectable seam
Patch seams first, then yes
Flaky goldens teach nothing
Function with 40+ branches, no tests
Yes, but time-box it
Gate tells you when coverage is enough
Behavior you are about to delete
No, add deletion tests after
Freezing a bug is counterproductive
Goldens freeze existing bugs, not correct behavior. That is intentional, and it is also a trap if you never revisit them.
Seam patching gets fragile. If collaborators are imported deeply, the harness grows faster than the refactor.
The mutation gate needs a fast test run. On a suite that takes minutes per case, this loop becomes unusable.
Skip this approach for prototypes, generated code, or any file scheduled for replacement. Also skip it if your team will not review the golden JSON in pull requests. Unreviewed goldens turn into noise nobody trusts.
Run the capture, run the gate, then make one small change. Ship the diff you can explain line by line. If you want a place to draft those first-pass cases, the free model access and free server option in MonkeyCode are a reasonable starting point.#testing #refactoring #python #ai #software #coding #development #engineering #inclusive #community
Make Each Characterization Test Fail Once Before You Refactor
I switched from Python to Guile as my go-to scripting language a few months ago and I've been enjoying it.
Pros:
- Guile is a Scheme
- Guile is slop-free
- Guile is faster than Python
- Guile can easily be embedded in other programs
- Guile easily compiles to WASM with Hoot
Cons:
- Guile's syntax can be less readable
- Guile's ecosystem is smaller
- Guile is less documented
Characterization Tests First, Then the Smallest Safe Change
Stop refactoring. Start recording. The smallest safe change wins only if you can prove nothing else moved.
That is the whole method. You freeze the hidden inputs, snapshot the current output, then change one line. The snapshot decides whether you were safe.
This article walks through a runnable loop on a small legacy stand-in module. Swap in your real module and the steps stay the same.
The ticket here is vague: unknown PLAN breaks invoice generation. Do not translate that into an architecture plan yet.
Translate it into one observable statement. "Unknown plan raises KeyError before any row is processed."
Now the statement is testable. It also tells you the bug lives in one lookup, not in the whole loop.
Legacy modules read two hidden inputs constantly: the clock and the environment. Both change between your laptop and CI.
Here is the stand-in under test. It is deliberately small and deliberately dirty.
# billing/cycle.py
import datetime
import os
RATES = {"standard": 1.0, "pro": 0.8, "legacy": 1.25}
def invoice_lines(rows):
today = datetime.date.today()
plan = os.environ.get("PLAN", "standard")
rate = RATES
[plan] out =
[] for row in rows:
days = (today - row["start"]).days
if days < 0:
days = 0
amount = round(row["units"] * rate * days, 2)
out.append({"id": row["id"], "days": days, "amount": amount})
return out
Two hidden inputs sit in four lines. datetime.date.today() reads the machine clock. os.environ.get reads the process environment.
Freeze both by patching the names inside the module under test. Never patch the stdlib module globally.
# tests/test_cycle_char.py
import datetime
import json
import os
import pathlib
import types
import pytest
from billing import cycle
GOLDEN = pathlib.Path(__file__).parent / "golden" / "invoice_lines.json"
class FixedDate(datetime.date):
@classmethod
def today(cls):
return cls(2026, 3, 1)
@pytest.fixture
def frozen(monkeypatch):
monkeypatch.setenv("PLAN", "pro")
monkeypatch.setattr(cycle, "datetime", types.SimpleNamespace(date=FixedDate))
This works because the module calls datetime.date.today() by attribute access. A module that does from datetime import date needs a different patch point.
That detail matters. Note it, or you will fight a passing test that proves nothing.
Write the rows once, run them, and save the output. The recorder is the source of truth, not your memory of the old behavior.
ROWS = [
{"id": "a1", "start": datetime.date(2026, 2, 1), "units": 3},
{"id": "a2", "start": datetime.date(2026, 3, 4), "units": 2},
{"id": "a3", "start": datetime.date(2026, 3, 1), "units": 0},
]
def test_invoice_lines_matches_golden(frozen):
got = cycle.invoice_lines(ROWS)
if os.environ.get("RECORD_GOLDEN") == "1":
GOLDEN.parent.mkdir(parents=True, exist_ok=True)
GOLDEN.write_text(json.dumps(got, indent=2))
assert got == json.loads(GOLDEN.read_text())
Record once with RECORD_GOLDEN=1 python -m pytest tests/test_cycle_char.py -q. The first run always passes, and that is expected.
Read the recorded file by hand before you commit it. A snapshot is not a truth claim.
[
{"id": "a1", "days": 28, "amount": 67.2},
{"id": "a2", "days": 0, "amount": 0.0},
{"id": "a3", "days": 0, "amount": 0.0}
]
Pin the error path too. Empty input still hits the lookup, so the exception fires before the loop.
def test_unknown_plan_raises_keyerror(monkeypatch, frozen):
monkeypatch.setenv("PLAN", "platinum")
with pytest.raises(KeyError):
cycle.invoice_lines([])
A test that cannot fail is decoration. Break a copy of the code and confirm the suite goes red.
rsync -a --exclude .git ./ /tmp/char-mut/
sed -i 's/if days < 0:/if days < -1:/' /tmp/char-mut/billing/cycle.py
cd /tmp/char-mut && python -m pytest tests/test_cycle_char.py -q; echo "exit=$?"
Expect exit=1. The clamped future date now leaks a negative days value, and the golden catches it.
If the suite still passes, your cases do not cover the branch. Fix that before touching the real module.
Smallest here is one expression. Replace the strict lookup with a guarded one.
- rate = RATES
[plan]+ rate = RATES.get(plan, RATES["standard"])
This changes observable behavior, so the pinned error test must change with it. Edit it deliberately, in the same commit.
-def test_unknown_plan_raises_keyerror(monkeypatch, frozen):
- monkeypatch.setenv("PLAN", "platinum")
- with pytest.raises(KeyError):
- cycle.invoice_lines([])
+def test_unknown_plan_falls_back_to_standard(monkeypatch, frozen):
+ monkeypatch.setenv("PLAN", "platinum")
+ assert cycle.invoice_lines([]) ==
[]Now the diff shows one intended behavior edit. Everything else stays green, which is the only proof you have.
Use Python 3.11 or newer here. Python 3.9 is already past its end-of-life date, so new test tooling should not target it.
Rank candidate changes by blast radius. Take rank 0 first, then climb one rung per commit.
Rank
Change
Lines touched
Gate to pass
0
Rename a local variable
1
goldens unchanged
1
Add a guard clause
1-3
goldens unchanged
2
Extract one pure helper
5-15
goldens unchanged, call order identical
3
Change observable behavior
1-5
exactly one pinned test edited on purpose
4
Move the module
many
old import path still pinned
5
Rewrite the module
all
stop, split into ranks 0-4
Rank 3 is the one people skip. They mix a behavior fix with a structure change and lose the ability to review either.
Set stop rules before you start. Seam hunting expands without limits otherwise.
Each stop is a signal to shrink scope, not to lower standards.
Drafting the edge-case rows in step 3 is the slow part. That is the part worth delegating.
I use MonkeyCode's free model access to propose candidate input rows and hidden-global guesses. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The free server option lets me run the mutation check on a repo copy without provisioning a machine of my own.
The model proposes. The recorder decides. Never let a model write the expected output from memory.
Free access and a free server option are the only two availability claims I make. I have not measured throughput or uptime, and a free tier is not an SLA.
Characterization tests pin current behavior, including bugs. They do not prove correctness and they do not replace intent-based tests.
Exact JSON equality is brittle with floats. Compare amounts with pytest.approx when your golden is hand-edited.
Clock patching only works when the module reads time by attribute access. Import styles, C extensions, and third-party clients may refuse the patch.
Skip this method if you are writing greenfield code, deleting the module next sprint, or have no way to execute it. Skip it if your team cannot review a behavior diff honestly.
If you run this loop on a repo copy, start with the recorder and keep it in charge of the truth.#testing #python #refactoring #legacycode #software #coding #development #engineering #inclusive #community
Characterization Tests First, Then the Smallest Safe Change
“If you find subprocess.run to be a little too verbose, you might consider writing a custom wrapper function or two for your own use cases.”
Read more 👉 https://pym.dev/running-subprocesses-in-python/
Build Your First LLM: A Hands-On Guide to Language Models by Hasan Degismez 📖 on Leanpub!
Learn how large language models work by building one from scratch. This hands-on guide walks you from first principles to a working Transformer you understand inside out.
Mixed None-and-raise APIs fail under model rewrites. The error taxonomy is the real product surface. Pin that taxonomy with characterization tests first, always.
Change one except clause only after the pin stays green. Happy-path unit tests will not save this refactor. Callers already branch on None, dict keys, and types.
Collapse any one of those shapes and production breaks. The defect is an unrecorded taxonomy, not missing types.
AI coding threads keep offering full-file cleanups. Those cleanups prefer one error type. They also prefer raising over returning None.
That preference is style, not evidence. A messy dispatcher often has three outcomes. Some inputs raise ValueError for bad payloads.
Some inputs return None after a send failure. Some inputs return {"ok": False, "status": 429}. Downstream code already checks all three shapes.
Loop-style agent edits make the same cut. They unify handlers because duplication looks sloppy. Duplication here is the published contract.
Record these four fields for every fixture. Skip prose messages on the first pass. Message strings drift across harmless edits.
None, mapping keys, or other.Types and keys usually stay stable. Status integers also stay stable. Log counts need a named logger, not the root.
The table below is the spec. It is a labeled example. It is not a production trace.
Fixture
Escapes
Return
Status
WARN+
empty body
RuntimeError
n/a
n/a
0
invalid JSON
ValueError
n/a
n/a
0
JSON list
ValueError
n/a
n/a
0
missing id
none
None
n/a
1
send TypeError
none
None
n/a
1
send TimeoutError
none
None
n/a
1
downstream 429
none
dict
429
1
downstream 200
none
dict
200
0
Keep the send TypeError row. That row is the trap. A cleaner except often drops it.
The code is a worked example. Run it locally before any extract. Do not treat it as measured field data.
# events.py — labeled example, not a live service
from __future__ import annotations
import json
import logging
from typing import Any, Callable
log = logging.getLogger("events")
SendFn = Callable[[dict], tuple[int, Any]]
def dispatch_event(raw: str | None, send: SendFn):
"""Messy contract: None, dict, or raise."""
if raw is None or raw == "":
raise RuntimeError("empty body")
try:
payload = json.loads(raw)
except Exception:
raise ValueError("bad json")
if not isinstance(payload, dict):
raise ValueError("bad json")
if "id" not in payload:
log.warning("missing id")
return None
try:
status, body = send(payload)
except Exception:
log.warning("send failed")
return None
if status >= 400:
log.warning("downstream %s", status)
return {"ok": False, "status": status, "body": body}
return {"ok": True, "status": status, "body": body}
# test_events_contract.py — worked example
import json
import logging
import pytest
from events import dispatch_event
def _records(caplog):
return [r for r in caplog.records if r.name == "events" and r.levelno >= logging.WARNING]
def _run(raw, send, caplog):
caplog.set_level(logging.WARNING, logger="events")
try:
value = dispatch_event(raw, send)
return None, value, _records(caplog)
except Exception as exc:
return type(exc), None, _records(caplog)
def test_empty_body_raises_runtime_error(caplog):
exc, value, recs = _run("", lambda p: (200, "ok"), caplog)
assert exc is RuntimeError
assert value is None
assert len(recs) == 0
@pytest.mark.parametrize("raw", ["{", "[]", "null"])
def test_bad_json_raises_value_error(raw, caplog):
exc, value, recs = _run(raw, lambda p: (200, "ok"), caplog)
assert exc is ValueError
assert value is None
assert len(recs) == 0
def test_missing_id_returns_none(caplog):
exc, value, recs = _run('{"name": "x"}', lambda p: (200, "ok"), caplog)
assert exc is None
assert value is None
assert len(recs) == 1
def test_send_type_error_returns_none(caplog):
def send(_payload):
raise TypeError("broken client")
exc, value, recs = _run('{"id": 1}', send, caplog)
assert exc is None
assert value is None
assert len(recs) == 1
def test_send_timeout_returns_none(caplog):
def send(_payload):
raise TimeoutError("late")
exc, value, recs = _run('{"id": 1}', send, caplog)
assert exc is None
assert value is None
assert len(recs) == 1
def test_downstream_429_is_dict(caplog):
exc, value, recs = _run('{"id": 1}', lambda p: (429, "slow"), caplog)
assert exc is None
assert value == {"ok": False, "status": 429, "body": "slow"}
assert len(recs) == 1
def test_downstream_200_is_dict(caplog):
exc, value, recs = _run('{"id": 1}', lambda p: (200, {"n": 1}), caplog)
assert exc is None
assert value == {"ok": True, "status": 200, "body": {"n": 1}}
assert len(recs) == 0
Run the file before editing handlers. Use a short traceback during the first pin.
python -m pytest test_events_contract.py -q --tb=short
A green suite with no mutation check is weak. You must see a failed unified-error fork. Keep that fork out of the merge.
# test_events_mutation.py — must fail against a unified raise rewrite
import events
def test_unified_raise_would_break_send_type_error(monkeypatch, caplog):
def rewritten(raw, send):
payload = __import__("json").loads(raw)
status, body = send(payload) # TypeError now escapes
return {"ok": status < 400, "status": status, "body": body}
monkeypatch.setattr(events, "dispatch_event", rewritten)
with pytest.raises(TypeError):
events.dispatch_event('{"id": 1}', lambda p: (_ for _ in ()).throw(TypeError("x")))
Expect this mutation test to fail on the rewrite. Restore the messy handler after that check. The failure is the evidence, not a vibe.
is None or catch types.except edit.Step two is not optional. Tests invented from the callee miss caller branches. Caller branches are the contract.
rg -n "dispatch_event\(" -g "*.py"
rg -n "is None|except ValueError|except RuntimeError" -g "*.py"
Record each hit as a fixture name. Missing hits become missing rows. Missing rows make unsafe extracts look safe.
Do not narrow except Exception on send first. The table says TypeError becomes None. Narrowing that clause raises TypeError instead.
That raise is a contract break. Extract the block without narrowing. Keep the same log line and None return.
def _send_or_none(payload, send):
try:
return send(payload)
except Exception:
log.warning("send failed")
return None
def dispatch_event(raw, send):
if raw is None or raw == "":
raise RuntimeError("empty body")
payload = _parse_object(raw)
if "id" not in payload:
log.warning("missing id")
return None
result = _send_or_none(payload, send)
if result is None:
return None
status, body = result
if status >= 400:
log.warning("downstream %s", status)
return {"ok": False, "status": status, "body": body}
return {"ok": True, "status": status, "body": body}
That extract is boring. Boring is the point. The taxonomy stays in the table.
A later change can narrow exceptions. Do that only with a version note. Add a row that expects TypeError to escape. Tell callers before you merge.
The JSON branch is different. json.loads should raise json.JSONDecodeError. Re-raising ValueError is the published type.
Narrowing except Exception to except json.JSONDecodeError can be safe. Prove it with the invalid JSON row. Prove it with the JSON list row too.
def _parse_object(raw):
try:
payload = json.loads(raw)
except json.JSONDecodeError:
raise ValueError("bad json") from None
if not isinstance(payload, dict):
raise ValueError("bad json")
return payload
Both bad-JSON fixtures must still raise ValueError. A leaked JSONDecodeError is a taxonomy change. Do not ship that leak without a caller audit.
from None also drops __cause__. Add a cause fixture if any caller reads it. Skip that fixture when no caller inspects causes.
Disclosure: This article was prepared as part of MonkeyCode's product outreach.
A model can draft the extract. It must not invent a new taxonomy. MonkeyCode provides free model access and a free server option.
Use either only after the characterization file is green. Feed the model the table and the test file. Ask for one extract, not a rewrite.
Reject a patch that removes a row. Reject a patch that changes None into a raise. This is not an agent loop.
One prompt. One diff. Same tests.
The harness does not prove semantic equality. It pins types, keys, status, and log counts. It misses timing, retry storms, and byte identity.
Log counts break if a library logs extra warnings. Pin the logger name events. Cap propagation on that logger.
Do not pin the root logger. Root pins go red on unrelated imports. That noise hides a real taxonomy drift.
The table is only as good as the fixtures. One unlisted caller path is an untested shape. Untested shapes are how "safe" extracts land in incident channels.
Do not use this flow for greenfield APIs. Design one error shape there. Do not preserve None plus raises on purpose.
Do not use this flow for security boundaries. Characterization will pin insecure behavior. Pinning is not hardening.
Do not use this flow without tests you can run offline. A model server cannot replace the table. If pytest cannot collect locally, stop.
Teams with a published OpenAPI error schema may skip dict-key rows. Use the schema as the table instead. Still pin process-local exception escapes.
HTTP schemas often omit those local raises. Omitting them is how ValueError turns into a 500. Keep the escape column anyway.
except.None callers still exist, or a version note ships.If a model patch violates any line, drop the patch. Rewrite pressure is not evidence. The table is.
If the characterization file is already green, one extract prompt on the free server is enough. Skip that prompt when the table still has empty cells.#python #testing #refactoring #ai #software #coding #development #engineering #inclusive #community
Freeze the Error Contract Before One except Change