Reference library

A/B testing & experimentation

User bucketing, experiment metrics, statistical comparison, and rollout guardrails.

7 matches
A/B testing & experimentation easy

How to Define a Mock Primary Metric in Python

Define a mock primary metric object with a name, value, and unit, and serialize it to a dictionary for experimentation and testing.

metrics mock ab-testing
Python
class Metric:
    def __init__(self, name, value, unit=None):
        self.name = name
        self.value = value
        self.unit = unit

    def to_dict(self):
        result = {"name": self.name, "value": self.value}
        if self.unit:
            result["unit"] = self.unit
        return result

    def __repr…
15 0 Open
A/B testing & experimentation easy

How to Evaluate Feature Flags in Python

A Python function that evaluates boolean feature flags with user-specific overrides, returning whether a flag is enabled and the reason for the decision.

feature flags ab testing experimentation
Python
import json

def evaluate_feature_flag(feature_name, context, flag_configs):
    """
    Evaluates a boolean feature flag given a context dictionary.

    Args:
        feature_name: The name of the feature flag.
        context: A dictionary of user/request context (e.g., {"user_id": "123"}).
        flag_configs: A …
14 0 Open
A/B testing & experimentation easy

How to Generate Multivariate JSON Mock Data in Python

This script generates mock multivariate JSON-compatible data with measurements and boolean flags for testing and experimentation pipelines.

json mock-data multivariate
Python
import json

def multivariate_mock(row_count: int = 3) -> list:
    """Generate mock multivariate data as list of JSON-compatible dicts."""
    records = []
    for i in range(row_count):
        record = {
            "id": i + 1,
            "measurements": {
                "temperature": 20.5 + i * 1.5,
          …
13 0 Open
A/B testing & experimentation easy

How to Mock a Remote Config Fetch in Python

Simulate a remote config API response with metadata, timestamps, and mock data for testing or local development.

mock config testing
Python
import json
from datetime import datetime
from typing import Any, Dict

def fetch_remote_config(mock_data: Dict[str, Any]) -> Dict[str, Any]:
    """Simulate fetching a remote config with metadata and timestamps."""
    return {
        "status": "success",
        "source": "mock",
        "fetched_at": datetime.utcn…
14 0 Open
A/B testing & experimentation easy

How to Mock an Exposure Event Log Record in Python

Generate a realistic exposure event record with UUID, UTC timestamp, and risk level for testing or experimentation.

mocking events testing
Python
import uuid
from datetime import datetime, timezone


def mock_exposure_event(person_id: str, location: str, duration_minutes: int) -> dict:
    return {
        "event_id": str(uuid.uuid4()),
        "person_id": person_id,
        "location": location,
        "duration_minutes": duration_minutes,
        "timestamp…
16 0 Open
A/B testing & experimentation medium

How to Perform Intent-to-Treat Analysis in Python

Runs an intent-to-treat analysis on mock A/B test data, comparing outcomes by initial group assignment with a t-test for significance.

ab-testing intent-to-treat statistics
Python
import pandas as pd
import numpy as np


def intent_to_treat_analysis(data):
    """Perform intent-to-treat (ITT) analysis.

    ITT compares outcomes based on initial treatment assignment,
    regardless of whether participants actually received the treatment.
    """
    # Create a copy to avoid mutating the origina…
13 0 Open
A/B testing & experimentation easy

How to create a global control holdout group in Python

This code implements a deterministic global control holdout group, randomly selecting a fraction of users to be excluded from feature rollouts for experiment validation.

ab-testing holdout global-control
Python
import random

class GlobalControl:
    def __init__(self, population_size, holdout_fraction=0.2, seed=42):
        random.seed(seed)
        self.population_size = population_size
        self.holdout_fraction = holdout_fraction
        self.holdout_size = int(population_size * holdout_fraction)
        self.holdout_…
11 0 Open

Browse by section

Each section groups closely related Python snippets.

A/B testing & experimentation — Python code examples

What you will find here

This page collects a/b testing & experimentation snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.