Bisect Good Bad Automation Script in Python

This Python script implements a binary search to find the first bad version in a list, simulating an automation script for git bisect.

Easy Python 3.9+ Aug 9, 2026 Git + Python 17 views 0 copies

Python code

29 lines
Python 3.9+
import bisect

def find_first_bad(versions):
    """Given a list of version objects with .is_bad(), find first bad version."""
    lo, hi = 0, len(versions)
    while lo < hi:
        mid = (lo + hi) // 2
        if versions[mid].is_bad():
            hi = mid
        else:
            lo = mid + 1
    return lo

class Version:
    def __init__(self, num, bad_start):
        self.num = num
        self.bad_start = bad_start

    def is_bad(self):
        return self.num >= self.bad_start

    def __repr__(self):
        return f"v{self.num}"

if __name__ == "__main__":
    bad_start = 7
    versions = [Version(i, bad_start) for i in range(1, 11)]
    first_bad = find_first_bad(versions)
    print(f"First bad version index: {first_bad} -> {versions[first_bad]}")

Output

stdout
First bad version index: 6 -> v7

How it works

The script uses a custom Version class with an is_bad() method to simulate version behavior. The binary search narrows down the first bad version by checking the middle element: if it's bad, move the high pointer down; otherwise, move the low pointer up. This guarantees O(log n) performance, making it efficient for large version histories. The output shows the index (6) and the actual version object (v7), confirming the first bad version.

Common mistakes

  • Using `bisect` module incorrectly instead of custom binary search
  • Off-by-one errors in the high bound, causing missing the last version
  • Assuming versions start at index 1 when using the result as an index

Variations

  1. Use `bisect.bisect_left` with a key function for simpler code
  2. Implement with recursive binary search for clarity

Real-world use cases

  • Automating git bisect to identify the commit that introduced a regression.
  • Finding the first failing test in a sequence of test runs during CI.
  • Locating the first incompatible change in a deployment pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.