python
32 lines · 7 steps
Generating product variants with itertools.product
Expand option groups into every combination, pricing each variant with per-option surcharges.
Explained by
highlit
1from itertools import product
2from dataclasses import dataclass
3from decimal import Decimal
4
5
6@dataclass(frozen=True)
7class Variant:
8 sku: str
9 options: dict[str, str]
10 price: Decimal
11
12
13def build_variants(base_sku: str, base_price: Decimal, option_groups: dict[str, list[str]]) -> list[Variant]:
14 surcharges = {
15 ("size", "XL"): Decimal("3.00"),
16 ("size", "XXL"): Decimal("5.00"),
17 ("material", "organic"): Decimal("4.50"),
18 }
19
20 names = list(option_groups)
21 variants: list[Variant] = []
22
23 for combo in product(*option_groups.values()):
24 selection = dict(zip(names, combo))
25 price = base_price + sum(
26 (surcharges.get(pair, Decimal("0")) for pair in selection.items()),
27 Decimal("0"),
28 )
29 suffix = "-".join(value.upper()[:3] for value in combo)
30 variants.append(Variant(sku=f"{base_sku}-{suffix}", options=selection, price=price))
31
32 return variants
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1itertools.product turns a mapping of option lists into every possible combination without nested loops.
- 2Zipping the original keys back onto each combo tuple restores which value belongs to which option.
- 3Using Decimal for money keeps surcharge arithmetic exact instead of drifting with float rounding.
Related explainers
python
import datetime from dataclasses import dataclass
Parsing fixed-width records in Python
parsing
generators
dataclasses
Intermediate
8 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/generating-product-variants-with-itertools-product-explained-python-4271/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.