Keep the Last N Python Records with a Bounded deque
A build report may need only the final twenty log records even though the build produced thousands. Converting the complete input to a list and slicing it keeps every record in memory first. A bounded collections.deque lets the report discard older records as it reads.
These examples use Python 3.10 or later and a finite input. “Last” means the final records in iteration order; the helper does not sort timestamps or select the most recent wall-clock times.
Retain a Suffix in Input Order
Save this helper as record_tail.py. It accepts a nonnegative built-in integer limit and returns a list containing at most that many records.
The zero case deliberately returns before touching the input. Rejecting booleans avoids accidentally treating True as a request for one record. This interface also rejects integer subclasses and non-integer numeric values rather than silently converting them.
Save this as show_tail.py beside the helper and run python show_tail.py.
Records in the result keep their original order. Duplicate values remain duplicates, and a limit larger than the input retains everything. The standard library documents bounded deque behavior and includes a file-tail recipe. Python deque documentation
Read a File While Its Context Is Open
Save this as tail_build_log.py beside the helper. Provide a UTF-8 build.log in the working directory, then run python tail_build_log.py.
The helper finishes reading inside the with block. The resulting list of strings remains usable after the file closes. Using end="" preserves the line endings supplied by text iteration without adding a blank line after each record. An unterminated final line stays unterminated in the output.
This reads from the file’s current position through the end. It scans the preceding lines even when only twenty are retained. It does not seek backward from the end or follow future appends. Text decoding errors propagate to the caller; print or publish the report only after the helper returns successfully.
Separate Retention Limits from Read Limits
A suffix cannot be known until a finite source ends. For a positive limit, the helper therefore consumes the entire input before returning. An infinite event feed never produces a final result through this interface. For a live display, maintain a deque in the event loop and take snapshots when the application requests them.
The container bounds the number of retained references, not the number of bytes. One enormous line or record can still use substantial memory. Source buffers and objects kept elsewhere are outside this retention limit. The final list adds a second container of references to the retained records during conversion; it does not deep-copy the records.
For M input records and a positive limit N, the scan takes O(M) container operations and retains O(min(M, N)) references, excluding the current input item and source buffering. Avoid list(records)[-limit:] as a replacement: it materializes the input, and a zero limit becomes [-0:], which selects the entire list.
Make Zero-Limit Consumption Explicit
Run this standalone example to compare the helper’s zero policy with constructing a zero-capacity deque directly.
| |
Both results are empty, but only the helper leaves the source untouched. Direct deque construction exhausts the finite iterable even when it retains nothing. That difference matters when iteration reads a file, performs work, or can raise an exception. Choose and document the policy instead of inferring consumption from the size of the result.
Test Against List Suffixes
Save this as test_record_tail.py beside the helper and run python test_record_tail.py.
| |
The list suffix provides a simple reference for finite test fixtures. These cases cover empty inputs, repeated values, oversized limits, argument errors, and the deliberate zero-consumption policy. The final identity assertion documents that retained mutable records remain shared objects; copy them separately if the report needs an independent snapshot of their contents.