How many times can I revisit three lines of code that are 20 years old?
“Human sorting” is sorting strings (usually file names) so that any numbers
in the names come out in the right order. For example, “file10.txt” should come
after “file2.txt”, but regular sorting will put them in the wrong order. I’ve
written twice before about the function to do this
(Human sorting and
Human sorting improved), but there’s more to say about
it.
One effect of AI these days is bug reports for obscure edge cases. As a
maintainer, it’s been a challenge first to read through them all, and then to
decide which ones deserve a fix. It’s tempting to fix every little thing no
matter how unlikely it is to happen in the real world. But every fix costs time,
energy and focus. Every fix comes with risks in the form of new bugs or changed
behavior. So some long-tail issues should be marked as “won’t fix.”
But this one intrigued me: if a file name includes a numeric component with
4301 digits, then the human sorting function fails. Buh?
Before we get to the current problem, here’s the original “buggy” code,
slightly simplified:
defhuman_key(s:str)->tuple[list[str|int],str]: """Turn a string into a sortable value that works how humans expect.
"z23A" -> (["z", 23, "A"], "z23A")
""" deftry_int(s:str)->str|int: """If `s` is a number, return an int, else `s` unchanged.""" try: returnint(s) exceptValueError: returns
defhuman_sorted(strings:Iterable[str])->list[str]: """Sort the given iterable of strings the way that humans expect.""" returnsorted(strings,key=human_key)
It splits the string into parts alternating between runs of digits and runs
of non-digits. It uses try_int on all of them, which turns the digits
into ints and leaves the non-digits as strings. That gives us a list of words
and numbers that can be compared to do the sort we need.
The problem now is with that 4301-digit run. Since 2022, Python’s
string-to-integer conversion has had a limit on the number of digits that can be
converted. This is to prevent denial of service attacks based on the quadratic
time to convert a string to an int. The default limit is 4300 digits. If a
string is longer than that, int() raises a ValueError.
But we were counting on ValueError to mean “this isn’t an integer”, and to
separate words from digits. Now that too-long number makes try_int return
the string un-converted, and using it as a sort key will try to compare an int
to a string, failing with:
TypeError: '<' not supported between instances of 'int' and 'str'
Of course, it’s absurd to be concerned that an actual file name will include
a run of more than 4300 digits. But I’ve been tweaking this function over
decades, and I like fiddling with it. The comments on the
original post offered a number of alternative implementations, a few of
which would have avoided this problem.
Rather than try to convert all of the parts of the name, we know from how
re.split works that the parts will alternate between words and numbers,
starting with a word even if it’s just an empty string. So we can attempt
conversion only for the parts that we know are digits.
First, we replace try_int with a function to safely convert digit
spans into numbers:
defnumber(s:str)->float: """Convert s to a number with no errors.""" try: returnint(s) exceptValueError: # This only happens if the number is too large to convert to an int. returnfloat("inf")
Now we can create split_key differently by only converting the
odd-numbered parts:
But isdigit() gets us into Unicode difficulties because \d and
isdigit() disagree on what count as digits. Something odd like
"a1²b" would be split into ['a', '1', '²b'], and
'²'.isdigit() is true, so now we’d be mistaking words for numbers.
In the end, though this is a long-tail bug, I fixed the human sort function;
it was a tiny isolated fix. Also, I don’t like having a function that works only
99.9999% of the time. And maybe it’s still not done: there are probably other
odd edge cases that could be a problem here. If I hear of those, I might make
more fixes.
The AI fire-hose of issues and pull requests requires me to exercise and
strengthen my “won’t fix” muscle. But I also get to choose where to make a fix
just because it pleases me.
Update:Jeff Epler suggested a few clever
alternatives. The 4300-digit limit is only applied to base 10 conversion. If we
interpret digit spans as base 16, there’s no limit on length, and the resulting
ints will sort the same as their base 10 counterparts. No helper function is
needed at all. As an added bonus, there are now no floats, so the type hinting
can be more straighforward. The result is satisfyingly compact:
def_human_key(s:str)->tuple[list[str|int],str]: """Turn a string into a list of string and number chunks.
"z23a" -> (["z", 35, "a"], "z23a")
Runs of digits are converted using base 16 because it has no digit limit, and the numbers will sort the same as if they were interpreted as base 10. The original string is appended as a last value to ensure the key is unique enough so that "x1y" and "x001y" can be distinguished. """ parts=re.split(r"(\d+)",s) split_key=[(int(p,base=16)ifi%2elsep)fori,pinenumerate(parts)] return(split_key,s)
defhuman_sorted(strings:Iterable[str])->list[str]: """Sort the given iterable of strings the way that humans expect.
Numeric components in the strings are sorted as numbers.
Returns the sorted list.
""" returnsorted(strings,key=_human_key)
Another of his suggestions was to use a different int() substitute. We
don’t need actual integers in the key, just something that will sort the same
way as integers. His idea was to turn digit runs into a tuple of (length,
value) with no conversion at all!
I haven’t done timings of any of these solutions. This last solution avoids
the quadratic time of integer conversion, but would likely be slower for the
real-world data we find in file names.
Today is Nat’s 37th birthday. We went to his group home yesterday to
celebrate. One of Nat’s favorite things to do when he’s with us is to bake with
Susan. So we had a baking party at his house to get everyone into the
activity:
At our house, the baking is from scratch, but Susan knew that would be too
much stuff to bring and too involved a process. An added complication is that
one housemate (MM) is diabetic but really wants to be part of things. So Susan
brought two box mixes: regular and sugar-free. Of course the fun is decorating,
so she also brought icing: chocolate and vanilla, both regular and sugar-free.
And candy for the top, including sugar-free sprinkles.
On weekends the guys are often visiting their families, but we wanted as many
of them there as possible. We put a sign on the fridge ahead of time, and
contacted some of the families to let them know it was happening. We were
delighted to have all of the housemates there.
We gave everyone aprons and paper chef’s hats to get them in the spirit.
Dressing up as bakers was fun all by itself. Everyone helped with the
ingredients and mixing, and only one egg ended up on the floor. The mood was
great: the guys were fascinated by the process (“what is batter?”), and excited
to be making cupcakes. We were all in a joking mood, including the staff.
One of Susan’s concerns was whether Nat would accept the changes: they don’t
usually bake at his group home, never use a box mix, he gets to lick the bowl
clean, and so on. But as set as he is in his ways, he is also used to “same”
things being done differently in different contexts. He went along with this
whole new way of baking.
With all the ingredients out on the table, we had to keep an eagle eye on MM
who wanted the sugar candy even though he shouldn’t eat it. In the end, he had
more than he should have, but less than he wanted.
Susan had brought food coloring and piping bags, but at the halfway point,
while the tins were in the oven, we made a game-time decision to simplify: plain
icing and butter knives for spreading would be fine.
When it came time to decorate, the guys created monstrosities with gummy
worms and M&Ms. Biggest surprise: no one wanted chocolate icing — it
was vanilla all around.
Looking back, we realized it didn’t even occur to us to bring candles or to
sing Happy Birthday! We brought Nat some presents to open, and the house was
headed out later to a birthday dinner, so I’m sure Nat had all the attention he
wanted.
We love these celebrations at Nat’s house. We feel close to all of his
housemates. I see them often since I am at the house to pick up or drop off Nat
a few times a week for various activities. One housemate refers to the others as
“brother”, though he can also tease in an edgy way. Overall, it feels like a
real home.
It can be a challenge to find the right living situation for a disabled son.
We have had ups and
downs over the years. His house
now is a good place. The guys feel like family, the staff feel like friends.
Going there almost always feels like a happy time.
How blog posts here indicate their age, and how I had too much fun with it.
Because I’ve been writing this blog for so long, I often share links to very
old posts. Three years ago, I added a feature: if the post is more than five
years old, there’s a message next to the dateline indicating the age.
The age descriptions adjust automatically when the post is rendered. I had
fun implementing the human-style age descriptions: “nearly 12 years”, “more than
seven years”, “exactly nine years”, etc:
NUMBER_NAMES=dict(enumerate( "zero one two three four five six seven eight nine ten".split() ))
The complete message is then something like “This is more than 14 years
old. Be careful” because many posts are technical, and details might have
shifted. For example: Tricky locals().
But some posts never become stale: they are evergreen. So back then I also
added a way to mark blog posts as evergreen. The message would change to
“This is eight years old, but it’s still good.” I marked blog posts
evergreen one by one when I shared them and saw the needless “Be careful”
warning.
Today I took it one step further: I made the “but it’s still good”
message customizable on each post. For example:
One of the things I like about running this site is that it is all mine. I
can change the software however I like. I can build features like this that
truly don’t matter, but they make me smile. And that is always good.
A git hook is a script in the .git directory of a git repo on your machine.
They run during various git operations. The important detail to understand about
hooks is that they do not get installed locally when you clone a repo. A newly
cloned repo never has active hooks. Hooks have to be enabled after cloning,
usually by you.
The attack Frank saw was dangerous because it wasn’t a cloned repo: it was a
local checkout that had hooks installed then shared as a Dropbox folder. So
when it landed on Frank’s machine, the hooks were active without him realizing
it.
Git hooks are not apparent: they are meant to sit quietly until they run and
ideally to be unobtrusive even then. But this attack made me want to know what
hooks were in each of my git directories.
In zsh, you can define a function called chpwd, and it
will execute whenever the current directory changes. Using this feature, I could
create a script that lists the active hooks when I change into a git
directory:
git_show_hooks(){ localgit_dir=$(gitrev-parse--absolute-git-dir2>/dev/null) if[[-z$git_dir]];then _git_shown_hooks_dir= return fi localhooks_dir=$(gitrev-parse--git-pathhooks) hooks_dir=${hooks_dir:a} # Only announce once per repo, not for every cd inside it. if[[$hooks_dir==$_git_shown_hooks_dir]];then return fi _git_shown_hooks_dir=$hooks_dir
local-ahooks localhook setoptlocaloptionsnullglob forhookin$hooks_dir/*;do if[[-f$hook&&-x$hook&&$hook!=*.sample]];then hooks+=(${hook:t}) fi done if(($#hooks));then echo-e"\e[31mgit hooks:\e[0m $hooks (from $git_dir)" fi }
Now entering a git repo I get an announcement of active hooks, if any. It’s
very rare to see a hook other than pre-commit, but if any are there, they will
be reported. The message will only be shown the first time I cd into a repo to
keep the noise down.
Once I had this in place, there was another git hook consideration I could
address: it’s common to have a .pre-commit-config.yaml file in a repo, but it’s
easy to forget to enable the pre-commit hook that will actually use the file.
Many developers probably have cloned repos where they haven’t enabled the
pre-commit hook, so the desired checks aren’t running.
A second chpwd function can look for the configuration file and let you know
if you have the pre-commit hook enabled:
git_check_precommit(){ localtoplevel=$(gitrev-parse--show-toplevel2>/dev/null) if[[-z$toplevel]];then _git_shown_precommit_dir= return fi # Only announce once per repo, not for every cd inside it. if[[$toplevel==$_git_shown_precommit_dir]];then return fi _git_shown_precommit_dir=$toplevel
if[[!-f$toplevel/.pre-commit-config.yaml]];then return fi localhooks_dir=$(gitrev-parse--git-pathhooks) hooks_dir=${hooks_dir:a} localpc_tool= if[[-f$hooks_dir/pre-commit]];then ifgrep-q'File generated by prek:'$hooks_dir/pre-commit2>/dev/null;then pc_tool=prek elifgrep-q'File generated by pre-commit:'$hooks_dir/pre-commit2>/dev/null;then pc_tool=pre-commit fi fi if[[-n$pc_tool]];then echo"$pc_tool installed" else echo-e"\e[31mpre-commit:\e[0m not installed,"\ "run 'pre-commit install' or 'prek install'"\ "($toplevel/.pre-commit-config.yaml)" fi }
add-zsh-hookchpwdgit_check_precommit
One more step, just to be extra safe: zsh doesn’t run the chpwd function when
starting a new shell. So we run the functions explicitly to check our initial
directory:
# Run them once on shell startup to check our starting directory. git_show_hooks git_check_precommit
These shell functions are keeping me aware of the enabled git hooks. The
messages might appear too often, and I might stop noticing them after a while,
but I think this is much better than not knowing what’s going on. I haven’t seen
any attacks, but I found at least one of my projects where I forgot to install
pre-commit.
Watching discussions happening online, I see a frequent unfortunate tic I’ll
call the Expert Asterisk. A beginner is asking for help, and experts are
answering. Then in the spirit of completeness, an expert throws in a fact or
detail far from the learner’s abilities or needs.
As an example, here was an interaction about git: a new learner was having
trouble getting properly oriented. They were asking how branches relate to
directories, and how to undo a change. They knew about git init but
didn’t know how it related to changing projects.
newb: so every time I change project I simply do ‘git init’ on them?
expert1: ‘git init’ is for creating a new project.
expert2: you change your working directory, typically, when you change project
So far so good, but then:
expert2: or you specify the git repo directory with the -C switch, but
it’s more typing to do, so hardly anyone does that unless there’s a very good
reason
What!? Why mention this while explicitly pointing out no one does it? The
newb just barely understands how git works at all. Why introduce obscure
command-line options that “hardly anyone” uses?
I call this an asterisk because it feels like an esoteric footnote that only
experts, academics, or completionists would need to know.
The expert is trying to be helpful. They are presenting all the options in
the optimistic hope that the newb will be able to pick and choose among them.
Worse, sometimes multiple experts each offer their own asterisks, and the
poor newb is intrigued and distracted by each one. The new learner doesn’t have
a way to sift out which details might be important to them. Their original
question gets lost in the spreading tangents.
It’s hard to help new learners: we can’t know where their gaps are. What
misconceptions need to be unwound? Often we have only a glimpse of their
context. Experts can miss when they use words slightly wrong, taking them at
face value instead of seeing the misunderstanding that leads down the wrong
path.
Notice in the exchange above, “change project” could mean switching among
existing projects or starting a new project. We’re not sure which they meant. An
expert will cycle among a number of active projects, but beginners will work on
one until it is done, then switch to a new project, never returning to the
previous one. Perhaps “every time I change project I do ‘git init’” was right
for their situation.
The -C comment didn’t derail the session, but the effort of that
comment could have instead been used to clarify the newb’s need.
I understand why experts add these asterisks to help sessions: they are
useful for some people even if not for this beginner, and experts are interested
(even fascinated) by all the intricate details. These discussion areas are not
strictly for newb-help. They’re for general discussion among many people.
There’s no rule against talking about advanced or rare options.
And it’s hard to know what will be useful, or what the newb really means, or
what will resonate with them to help them find a solution. It’s all
difficult.
But you should at least recognize who you are addressing and whether you are
helping them. If you want to help the beginner, try to resist the impulse to add
little-traveled tangents. Focus on the question at hand and try hard to
understand the newb’s situation and mindset. Speak their language so they can
hear you.
This is a lightning talk I did at PyCon US 2026: Silence is Golden. The
overall message is to leave some quiet time so that reluctant speakers have a
chance to participate. I start with a jokey disclaimer because I followed Simon
Willison who gave an energetic, entertaining, and loud(!) speed-run through a
year of progress in LLMs:
I do these talks and blog posts about how to better interact with people, but
I hope they don’t come off as too preachy. I have to remind myself to keep these
ideas top of mind. I am one of those people who speak easily that I describe in
the lightning talk. I have to remember to hold back, to leave time and space for
other people.
I had the idea for this lightning talk a few years ago at PyCon, while
watching things going wrong. I was in a room with a few dozen people. The goal
in the room was to hear from lots of people, but the leader of the discussion
was a “speaks easily” kind of person, and I could see the dynamic of the room
failing to make space for everyone.
I was really pleased to be able to extend the time-tested and well-known
Pac-Man Rule from space to time. It made for an
interesting hook, making the talk more interesting than just a scold.
It’s really hard to keep quiet. But it’s important sometimes.