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
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 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.