Skip to content

Hreflang Tag Generator — Python source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

# hreflang-tag-generator — pure locale-list validation + alternate-link
# emission (SEO/meta trio). Authored snippet mirroring src/lib/hreflang.ts:
# normalize_locale + build_hreflang are a pure port of the TS grammar — the
# ll/ll-CC case-correcting locale rules, the row-located error strings,
# x-default appended last, and both output flavors (HTML <link> block and
# XML sitemap <xhtml:link> block, indentation and self-closing style
# included).
from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import List, Optional

_SINGLE_RE = re.compile(r"^([a-zA-Z]{2})$")
_REGION_RE = re.compile(r"^([a-zA-Z]{2})-([a-zA-Z]{2})$")
_URL_RE = re.compile(r"^https?://")


@dataclass
class HreflangRow:
    """One locale/URL pair. Mirrors the TS HreflangRow interface."""

    locale: str
    url: str


@dataclass
class HreflangInput:
    """The field set for build_hreflang — rows plus an optional x-default."""

    rows: List[HreflangRow] = field(default_factory=list)
    x_default_url: Optional[str] = None


@dataclass
class HreflangResult:
    """Diagnostics plus both emitted flavors. On failure ok is False,
    errors lists every row-located problem, and normalized/html/sitemap
    are empty — exactly like the TS result."""

    ok: bool
    errors: List[str]
    normalized: List[HreflangRow]
    html: str
    sitemap: str


def normalize_locale(raw: str) -> Optional[str]:
    """Normalize a locale tag to Google's hreflang grammar: `ll` (ISO-639-1,
    lowercase) or `ll-CC` (region uppercase, ISO-3166). Case and surrounding
    whitespace are corrected (`en-us` -> `en-US`); anything else is invalid
    and returns None. The Python twin of normalizeLocale() in
    src/lib/hreflang.ts — None stands in for the TS null."""
    t = raw.strip()
    if m := _SINGLE_RE.match(t):
        return m.group(1).lower()
    if m := _REGION_RE.match(t):
        return f"{m.group(1).lower()}-{m.group(2).upper()}"
    return None


def _valid_url(raw: str) -> Optional[str]:
    """Trim raw and return it when it starts with http:// or https://,
    otherwise None. Mirrors the TS validUrl() helper."""
    t = raw.strip()
    return t if _URL_RE.match(t) else None


def build_hreflang(inp: HreflangInput) -> HreflangResult:
    """Validate a locale/URL table and emit both hreflang flavors. Invalid
    input collects every error (row-located) and emits empty blocks; valid
    input normalizes locales, preserves row order, and appends x-default
    last."""
    errors: List[str] = []
    normalized: List[HreflangRow] = []
    seen: set[str] = set()

    for i, row in enumerate(inp.rows):
        n = i + 1
        locale = normalize_locale(row.locale or "")
        if locale is None:
            errors.append(
                f'Row {n}: "{(row.locale or "").strip()}" is not a valid locale'
                " — use ll or ll-CC (e.g. en, de-AT)."
            )
            continue
        if locale in seen:
            errors.append(f'Row {n}: locale "{locale}" is already used.')
            continue
        if not row.url or not row.url.strip():
            errors.append(f"Row {n}: URL is required.")
            continue
        url = _valid_url(row.url)
        if url is None:
            errors.append(f"Row {n}: URL must start with http:// or https://.")
            continue
        seen.add(locale)
        normalized.append(HreflangRow(locale=locale, url=url))

    x_default: Optional[str] = None
    if inp.x_default_url and inp.x_default_url.strip():
        x_default = _valid_url(inp.x_default_url)
        if x_default is None:
            errors.append("x-default: URL must start with http:// or https://.")

    if errors:
        return HreflangResult(ok=False, errors=errors, normalized=[], html="", sitemap="")

    html_lines = [
        f'<link rel="alternate" href="{r.url}" hreflang="{r.locale}" />'
        for r in normalized
    ]
    sitemap_lines = [
        f'    <xhtml:link rel="alternate" hreflang="{r.locale}" href="{r.url}"/>'
        for r in normalized
    ]
    if x_default is not None:
        html_lines.append(f'<link rel="alternate" href="{x_default}" hreflang="x-default" />')
        sitemap_lines.append(
            f'    <xhtml:link rel="alternate" hreflang="x-default" href="{x_default}"/>'
        )

    return HreflangResult(
        ok=True,
        errors=[],
        normalized=normalized,
        html="\n".join(html_lines),
        sitemap="\n".join(sitemap_lines),
    )

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →