Frame 10 Comes Before Frame 2: Define a Filename Ordering Policy
Original code, local tests and clear limits for Python natural sort frame filenames. Separate observed results from proposed integration.

Write the intended sequence before choosing a sorter
Start with three names: frame2.png, frame10.png and frame1.png. Our baseline test passes them to Python's ordinary sorted function and gets frame1.png, frame10.png, frame2.png. That is a valid lexical result. The defect is a mismatch between that rule and the sequence this project wants to show. Write the desired list as frame1.png, frame2.png, frame10.png before changing the code. It gives the later assertion a concrete target rather than the vague requirement that filenames should look natural.
The next test supplies the same list to order_frames and expects the desired sequence. This is a local string-ordering example, not a frame-extraction experiment. The helper does not open the PNGs, inspect their pixels or read a video. The lead photograph contains contact prints of a terracotta toy boat labeled 1, 2 and 10 beside a brass ruler. Those are illustrative props. They make the sequencing question recognizable without pretending that the Python function generated the photographs or recovered frames from footage.
A filename can carry several kinds of numbers, and the desired interpretation should be decided by the project. frame10 might mean a sequence index, while another naming scheme could use a take number, camera number or date component. Our rule treats every ASCII digit run as an unsigned integer component, regardless of what a person intended it to mean. It has no knowledge of camera metadata or elapsed time. That limited rule is useful only where the chosen names already encode a sequence you want to compare that way.
Keep sequence order separate from asset identity. Two files in different directories can share the same basename, and a sort of those basename strings cannot decide which file a project should open. Likewise, a successful sort does not prove that frame1 was captured before frame2. Exporters can rename files, skip numbers or combine sessions. A proposed media-project viewer should display the chosen sequence as filename order unless it actually has a separate timestamp contract. The current helper supplies only the name-ordering part.
Before adopting the function, write down answers for leading zeros, case differences, multiple numbers, non-ASCII digits and duplicate names. The original suite records several choices, and the added contract suite makes some less obvious boundaries visible. These answers are not universal rules for all archives. They are the policy this code implements. If your desired list differs for one of those cases, change the policy deliberately and give that case its own expected result instead of describing the existing output as mysteriously wrong.
Python sorting accepts a key function and compares the resulting keys. The application must define the interpretation encoded in those keys. Python 3.12 Sorting HOWTO
The baseline is worth preserving after the fix. test_lexical_baseline keeps the 1, 10, 2 result, while test_digit_runs keeps the 1, 2, 10 result from the custom helper. Together they explain why the extra key function exists. Removing the baseline would not necessarily break sorting, but it would remove the compact reproduction of the original mismatch. It also helps a later maintainer see that Python's lexical sorter was not malfunctioning; we supplied a different interpretation for this particular naming convention.
Read the tagged key from left to right
frame_key first requires a string. It then splits the name with the regular expression ([0-9]+), whose capturing group preserves the ASCII digit runs as parts of the split result. Empty parts are skipped. A digit run becomes a tuple beginning with tag 1, followed by its integer value and its original length. A remaining text part becomes a tuple beginning with tag 0, followed by its casefolded text. The function returns the sequence of these tokens together with the original name as a final tie-breaker.
For frame2.png, the token sequence has the text frame, numeric value 2 with length 1, and text .png. For frame10.png, the numeric value is 10 with length 2. The leading text tokens match, so the numeric value decides which name comes first. This compares 2 with 10 rather than comparing the first character of the digit strings. The recorded frame-key-samples.json retains actual key outputs from the helper for selected strings. It is a trace of the string algorithm, not an inventory of image files found on disk.
The numeric and text tags make the token shape explicit. When token positions contain different categories, the tags decide the category order before Python needs to compare the category-specific values. In this policy, text tag 0 precedes numeric tag 1 at a differing token position. That is another application choice rather than a claim about how every natural-sort library behaves. Do not remove the tags and expect arbitrary mixtures of raw strings and integers to retain this key's comparison contract.
Length matters only after numeric values match. frame1.png, frame01.png and frame001.png have equal numeric value 1, but their digit-run lengths are 1, 2 and 3. test_leading_zero_policy therefore expects the shorter spelling first. This is not an integer-formatting operation: the helper does not rename frame001.png or strip its zeros from the returned name. The original strings remain the output values. The integer conversion is used inside the comparison key, while the source spelling is retained for display and later file selection.
The multiple-run fixture uses scene2-shot10, scene2-shot2 and scene10-shot1. The comparison proceeds through the token sequence in order. The first numeric run keeps both scene2 names before scene10, then the second run puts shot2 before shot10. The numbers are not added together, and the helper does not decide that shot1 from scene10 belongs next to shot2 from scene2. If the project needs a different grouping, such as all camera angles for each shot, that grouping must be represented explicitly rather than inferred from the word natural.
For letter-case ties, the primary text tokens use casefold, but the returned key also contains the original name. In test_case_tie_uses_original_name, the input f2 followed by F2 becomes F2 followed by f2. A stable sort by folded tokens alone would retain a different input-dependent tie order for that list. Our final original-name component chooses a specific tie policy. This does not make case differences unimportant to storage; two distinct spellings remain two output strings, and the helper does not merge them.
The Arabic digit ٢ is outside the regular expression's ASCII range and remains in a literal text part. test_non_ascii_digits_are_literal expects frame2 before frame٢ under the actual tagged keys. Do not read that result as an Arabic-language sorting rule or a numerical comparison of the two digit characters. If a project needs a broader numeric interpretation, it must define which characters and combinations are accepted and add cases for them. The current test deliberately documents the narrower behavior instead of claiming locale-aware collation.
frame_order.py
import re
def frame_key(name):
if not isinstance(name,str):
raise TypeError('Expected a frame name')
tokens=tuple((1,int(part),len(part)) if part.isascii() and part.isdigit()
else (0,part.casefold()) for part in re.split(r'([0-9]+)',name) if part)
return tokens,name
def order_frames(names):
return sorted(names,key=frame_key)
The original 9 methods and a further 5 contract methods passed locally on Python 3.12.3 for Windows. They operate on name strings only. Actual sample keys and output lists are retained with the source. No filesystem discovery, contact-sheet rendering, video generation or performance test was run.
Try names that could mean something else
Five additional methods probe boundaries that the 1, 2, 10 example does not settle. The first uses frame2.10 and frame2.2. Our helper places frame2.2 first because the dot separates two digit runs and the final values compare as 2 before 10. This is not decimal-number parsing: the text 2.10 could have a different numerical meaning if interpreted as one decimal value. The filename policy operates on components. The test records that distinction so that a future caller does not mistake a component sorter for a general numeric-expression parser.
The next method uses frame-10 and frame-2. The hyphen remains a literal part of the shared text prefix, and the positive digit-run values put frame-2 before frame-10. If someone intended the suffixes as negative numbers, this would not be their desired mathematical order. The helper has not parsed a sign. That boundary belongs in the contract rather than a hidden exception that guesses the meaning of punctuation. A naming scheme with signed coordinates should supply a parser for its defined fields, not assume the current string splitter understands coordinates.
test_duplicate_names_are_retained supplies f2, f1 and f2 and receives f1, f2, f2. Sorting is not deduplication. If two identical names came from two distinct source directories, removing one would lose a selection unless the caller retained their identities separately. If the repeated string is an accidental duplicate entry, a caller can apply a separately chosen rule before layout. The helper does neither operation. Its output length preserves the repeated entries in this fixture instead of treating a comparison tie as a reason to discard an item.
test_empty_name_is_not_filtered supplies f1 and the empty string. The empty name sorts first because its token sequence is empty. The string-type guard does not require a non-empty value. That may be inappropriate for a proposed file-picker workflow, but it is the behavior of the current API. If the caller wants only named images, filter or reject empty names in a declared input step and test that step. An empty-list test alone would never establish whether empty elements are accepted, so the additional case answers a distinct question.
test_path_objects_are_not_accepted passes a pathlib.Path object and expects TypeError. The helper accepts name strings, not path objects. A proposed discovery layer might select path.name for basename ordering or use a larger record key that includes a source identifier. Converting the full path to a string is another possible choice, but it means directory names and their digit runs also enter the sort. Decide which representation is meant before calling the helper. This function cannot infer that choice from an arbitrary Path object.
These added cases did not require changing the implementation. They made the existing comparison rule more explicit. The original nine methods and the additional five methods total 14 distinct local methods. There is no timing comparison, operating-system directory scan or contact-sheet renderer hidden inside that count. The cases are deliberately small enough that a reader can compare the input and expected output directly. They are useful evidence for adopting or rejecting this naming policy without claiming that it covers every naming convention.
Read the rest of the original checks as small contracts
Besides the lexical and numeric examples, test_empty_input verifies that an empty list produces an empty list. That is different from the additional empty-name case, where the list contains a string with no characters. A proposed viewer can therefore distinguish having no selected assets from having an invalid or blank asset label in its selection. The helper itself does not show a user message for either state. It returns ordered strings, leaving the caller to decide which states are acceptable before a layout or export operation begins.
test_original_list_unchanged calls order_frames with f10 and f2, then checks that the original list still has its original order. The helper uses sorted rather than rearranging that input list in place. This observation does not make the list immutable, protect it from another component or establish thread safety. It simply means this function did not reorder that supplied list during the tested call. A caller can keep the original selection order alongside the returned filename order if both views matter to the proposed interface.
test_nonstring_rejected passes an integer element and expects TypeError. That guard prevents this helper from silently converting an unexpected value into a name. It does not validate that a string names a real file, has an allowed extension or represents an image. The additional Path-object case is another way to see the same boundary from a common caller type. Keep the distinction between validating the representation supplied to the sorter and validating a file selected by a user. The latter operation does not occur in this code.
The leading-zero, multiple-run, case-tie and non-ASCII cases specify comparison details rather than repairing independent Python defects. A proposed project might prefer the original input order for folded ties, or reject names that mix numbering systems. Those would be different expected outputs with a different contract. The supplied suite makes the current choices reviewable: a maintainer can identify exactly which assertion should change when the project intentionally changes its naming rules, instead of replacing the key function and hoping that a contact sheet still looks plausible.
The recorded environment is Python 3.12.3 on Windows. The sorter operates on supplied strings and makes no filesystem calls, so this record should not be expanded into a claim about a tested archive on every operating system. We retained the source, named assertions, actual outputs and run records. That is enough to reproduce the defined lists. It does not measure filename discovery speed, Unicode normalization behavior or the fidelity of any image associated with one of those names.
Design the proposed contact-sheet input as records, not bare names
Suppose a future project selects images from two directories. A useful proposed record can contain a source identifier, a full path and a display name. Order the records by a deliberately selected name key while retaining the path on each record for opening the correct source. This is a design exercise; our helper only orders strings and does not create those records. The distinction prevents a common integration mistake in which names are sorted separately and later zipped back to paths that remained in their old order.
For example, two hypothetical records might both have display name frame2.png but refer to different session directories. A basename-only ordering policy produces a tie. The record-level design must decide how to resolve it, perhaps with a stable source identifier after the name key or by grouping sessions first. Do not guess a capture-time order from the directory spelling. The current duplicate-string test retains both entries, but it has no path association to preserve because its inputs are only strings. A record-level adapter would need its own association assertions.
Perform proposed discovery and filtering before arranging the contact sheet. The application might accept only selected extensions, skip directories, reject blank display names or require one session per sheet. None of those decisions belongs secretly inside frame_key. The additional empty-string and Path-object cases show why a caller must prepare inputs intentionally. Passing an extension filter does not validate the image contents, and getting a name into numerical order does not prove that its underlying image can be decoded. Keep each result tied to the operation that actually produced it.
A proposed layout can annotate each cell with its filename and a separate display position. Those are different values: the third cell might contain frame10.png, while its layout position is 3. A sequence with missing names can still be laid out; it does not follow that the missing files should be generated or silently renumbered. The helper does not demand consecutive numbers. Write the expected ordered list first, then let the layout enumerate the returned records without inventing a claim about how many frames were captured.
The guide to preserving complete project files during output replacement addresses a separate file-writing problem. A proposed manifest writer can use that completed-output approach after it has constructed the intended sequence. A completely written manifest can still contain the wrong order, just as a correctly sorted list can refer to a missing file. These properties need separate checks. Our original code verifies the ordering policy on supplied names, and the linked project verifies its own staging-file behavior; neither result automatically supplies the other application's missing integration layer.
If a project later exports a video from the selection, filename order is only one input to that workflow. The application would also need an explicit rate or timing contract, image dimensions and an encoder integration. We did not run that workflow, extract real frames or generate a video. The printed boat contact photos illustrate sequence planning. They do not demonstrate motion, duration or alignment with audio. A proposed video experiment should preserve its actual outputs and record those additional decisions when the tool and implementation are available.
Save the policy and reproduce it before changing old projects
Keep frame_order.py, test_example.py and test_contract.py together in your copied example directory. The original test module contains 9 methods and the added module contains 5. From that directory, python -m unittest discover -s . -p test_example.py -v runs the original suite; the corresponding command with test_contract.py runs the added cases. These are reproduction instructions for your copy. The saved execution records include the actual interpreter and absolute discovery directories used locally, plus source hashes for the code that was checked.
A project manifest can propose a policy name such as ascii-runs-short-zeros-v1 and retain a few expected-name sequences. That name is not generated by the current helper and does not alter its output. It is a caller-facing way to remember that ASCII digit runs, shorter zero-padded forms and original-name ties were chosen. Retain a case that matters to the project instead of relying only on an implementation version number. A function could keep its public name while its regex or tie rules change, producing a different order for an old archive.
Before changing the policy, compare expected lists for the original 1, 2, 10 case, a zero-padded case, a multiple-run case and the added punctuation boundaries. If a project begins using signed coordinates, the minus-literal case should force a deliberate choice rather than allowing the old helper to be relabeled as coordinate-aware. If broader digits are added, keep the old Arabic-digit fixture as a documented behavior change. Such changes may be appropriate, but they should not silently reinterpret every stored project as though the previous order had never existed.
The actual frame-key-samples.json can help inspect a mismatch at the token level. Compare the digit-run value and length, the text token and the final original-name tie-breaker rather than staring only at the sorted result. If the input record carried a full path instead of a basename, inspect that preparation boundary too. The recorded sample keys do not contain private archive paths or image content; they describe the small names supplied for this example. A proposed diagnostic interface can expose similarly limited comparison details without dumping an entire asset catalog.
At handoff, keep the selected input representation, expected sequence and policy version together. State that discovery, image decoding, contact-sheet composition and video export are separate planned components if they have not been implemented. The current project is complete for its smaller job: reproducing lexical 1, 10, 2 order and supplying a tested ASCII digit-run policy with visible edge cases. That gives a media application an explicit ordering decision it can integrate and test, instead of an unexplained promise that every file called a frame will appear in its true chronological position.
test_example.py
import unittest
from frame_order import order_frames
class SortTests(unittest.TestCase):
def test_lexical_baseline(self):self.assertEqual(sorted(['frame2.png','frame10.png','frame1.png']),['frame1.png','frame10.png','frame2.png'])
def test_digit_runs(self):self.assertEqual(order_frames(['frame2.png','frame10.png','frame1.png']),['frame1.png','frame2.png','frame10.png'])
def test_leading_zero_policy(self):self.assertEqual(order_frames(['frame001.png','frame01.png','frame1.png']),['frame1.png','frame01.png','frame001.png'])
def test_multiple_runs(self):self.assertEqual(order_frames(['scene2-shot10','scene2-shot2','scene10-shot1']),['scene2-shot2','scene2-shot10','scene10-shot1'])
def test_empty_input(self):self.assertEqual(order_frames([]),[])
def test_original_list_unchanged(self):
values=['f10','f2'];order_frames(values);self.assertEqual(values,['f10','f2'])
def test_case_tie_uses_original_name(self):self.assertEqual(order_frames(['f2','F2']),['F2','f2'])
def test_non_ascii_digits_are_literal(self):self.assertEqual(order_frames(['frame٢','frame2']),['frame2','frame٢'])
def test_nonstring_rejected(self):
with self.assertRaises(TypeError):order_frames([1])
test_contract.py
from pathlib import Path
import unittest
from frame_order import order_frames
class NamingContractTests(unittest.TestCase):
def test_dots_separate_digit_runs_not_decimal_values(self):
self.assertEqual(order_frames(['frame2.10','frame2.2']),['frame2.2','frame2.10'])
def test_minus_is_literal_not_a_negative_sign(self):
self.assertEqual(order_frames(['frame-10','frame-2']),['frame-2','frame-10'])
def test_duplicate_names_are_retained(self):
self.assertEqual(order_frames(['f2','f1','f2']),['f1','f2','f2'])
def test_empty_name_is_not_filtered(self):
self.assertEqual(order_frames(['f1','']),['','f1'])
def test_path_objects_are_not_accepted(self):
with self.assertRaises(TypeError):order_frames([Path('frame1.png')])
Prepared with AI assistance and automated reviews. The original code was run locally within the recorded test scope. The lead image is illustrative; it is not a field photograph or evidence of a browser, spreadsheet or video test.



