Skip to content

fmt

pinky_core.fmt

Pure formatting utility functions.

No external dependencies — importable without a Snowflake connection. Safe to use in SP/UDF handlers, Streamlit apps, and local scripts.

AddressComponents dataclass

Parsed components of a postal address.

Raw fields preserve the original casing of the input. afnor contains the same fields normalised per NF Z10-011 (FR only).

Attributes:

Name Type Description
number str | None

Street number ("12").

repetition_index str | None

Repetition suffix, normalised — "BIS", "TER", "QUATER" (FR) or occupancy identifier (US).

street_type str | None

Street type in original casing ("Rue", "avenue"…).

street_name str | None

Street name in original casing ("des Lilas").

zip_code str | None

Postal code — provided or extracted from the address string.

city str | None

City name in original casing.

afnor AfnorAddress | None

AFNOR-normalised fields (FR only) — see AfnorAddress.

raw str | None

Original input; always set.

Source code in src/pinky_core/fmt.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
@dataclass
class AddressComponents:
    """Parsed components of a postal address.

    Raw fields preserve the original casing of the input.
    ``afnor`` contains the same fields normalised per NF Z10-011 (FR only).

    Attributes:
        number:           Street number (``"12"``).
        repetition_index: Repetition suffix, normalised — ``"BIS"``, ``"TER"``,
                          ``"QUATER"`` (FR) or occupancy identifier (US).
        street_type:      Street type in original casing (``"Rue"``, ``"avenue"``…).
        street_name:      Street name in original casing (``"des Lilas"``).
        zip_code:         Postal code — provided or extracted from the address string.
        city:             City name in original casing.
        afnor:            AFNOR-normalised fields (FR only) — see ``AfnorAddress``.
        raw:              Original input; always set.
    """

    number: str | None = None
    repetition_index: str | None = None
    street_type: str | None = None
    street_name: str | None = None
    zip_code: str | None = None
    city: str | None = None
    afnor: AfnorAddress | None = None
    raw: str | None = None

AfnorAddress dataclass

AFNOR NF Z10-011 normalised address components (FR only).

All string fields are unidecode + uppercase. Analogous to e164_format on phone numbers — use these fields when the target system (ADP, La Poste…) requires the normalised form.

Attributes:

Name Type Description
number str | None

Street number ("12").

repetition_index str | None

Abbreviated suffix — "B" (BIS), "T" (TER), "Q" (QUATER).

street_type str | None

Uppercase street type — "RUE", "AVENUE"

street_name str | None

Uppercase street name — "DES LILAS".

zip_code str | None

Postal code (unchanged).

city str | None

Uppercase city — "PARIS".

Source code in src/pinky_core/fmt.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
@dataclass
class AfnorAddress:
    """AFNOR NF Z10-011 normalised address components (FR only).

    All string fields are unidecode + uppercase.  Analogous to ``e164_format``
    on phone numbers — use these fields when the target system (ADP, La Poste…)
    requires the normalised form.

    Attributes:
        number:           Street number (``"12"``).
        repetition_index: Abbreviated suffix — ``"B"`` (BIS), ``"T"`` (TER),
                          ``"Q"`` (QUATER).
        street_type:      Uppercase street type — ``"RUE"``, ``"AVENUE"``…
        street_name:      Uppercase street name — ``"DES LILAS"``.
        zip_code:         Postal code (unchanged).
        city:             Uppercase city — ``"PARIS"``.
    """

    number: str | None = None
    repetition_index: str | None = None
    street_type: str | None = None
    street_name: str | None = None
    zip_code: str | None = None
    city: str | None = None

deduplicate_headers(headers)

Deduplicate a list of column headers by appending a counter suffix.

Example

["A", "B", "A", "A"] → ["A", "B", "A_1", "A_2"]

Parameters:

Name Type Description Default
headers list[str]

List of header strings (already normalised).

required

Returns:

Type Description
list[str]

List with duplicates resolved by appending _1, _2, etc.

Source code in src/pinky_core/fmt.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def deduplicate_headers(headers: list[str]) -> list[str]:
    """Deduplicate a list of column headers by appending a counter suffix.

    Example:
        ["A", "B", "A", "A"] → ["A", "B", "A_1", "A_2"]

    Args:
        headers: List of header strings (already normalised).

    Returns:
        List with duplicates resolved by appending _1, _2, etc.
    """
    seen: dict[str, int] = {}
    result: list[str] = []
    for h in headers:
        if h in seen:
            seen[h] += 1
            result.append(f"{h}_{seen[h]}")
        else:
            seen[h] = 0
            result.append(h)
    return result

format_boolean(value, style='check')

Format a boolean as a readable icon (tri-state: True / False / None).

Parameters:

Name Type Description Default
value bool | None

Boolean value. None = indeterminate.

required
style str

Rendering style, one of: - "check" → ✅ / ❌ / ☑️ - "yesno" → Yes / No / — - "onoff" → ON / OFF / — - "dot" → 🟢 / 🔴 / ⚪

'check'

Returns:

Type Description
str

Formatted string for the given style.

Source code in src/pinky_core/fmt.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def format_boolean(value: bool | None, style: str = "check") -> str:
    """Format a boolean as a readable icon (tri-state: True / False / None).

    Args:
        value: Boolean value. None = indeterminate.
        style: Rendering style, one of:
               - "check" → ✅ / ❌ / ☑️
               - "yesno" → Yes / No / —
               - "onoff" → ON / OFF / —
               - "dot"   → 🟢 / 🔴 / ⚪

    Returns:
        Formatted string for the given style.
    """
    styles: dict[str, tuple[str, str, str]] = {
        "check": ("✅", "❌", "☑️"),
        "yesno": ("Yes", "No", "—"),
        "onoff": ("ON", "OFF", "—"),
        "dot": ("🟢", "🔴", "⚪"),
    }
    true_val, false_val, none_val = styles.get(style, styles["check"])
    if value is None:
        return none_val
    return true_val if value else false_val

format_date(d, fmt='%d/%m/%Y')

Format a date as a readable string.

Parameters:

Name Type Description Default
d date | datetime | None

Date to format. Returns "" if None.

required
fmt str

strftime format string. Defaults to dd/mm/yyyy.

'%d/%m/%Y'

Returns:

Type Description
str

Formatted date string, or "" if d is None.

Source code in src/pinky_core/fmt.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def format_date(d: date | datetime | None, fmt: str = "%d/%m/%Y") -> str:
    """Format a date as a readable string.

    Args:
        d:   Date to format. Returns "" if None.
        fmt: strftime format string. Defaults to dd/mm/yyyy.

    Returns:
        Formatted date string, or "" if d is None.
    """
    if d is None:
        return ""
    return d.strftime(fmt)

format_datetime(d, fmt='%d/%m/%Y %H:%M')

Format a datetime as a readable string with time.

Parameters:

Name Type Description Default
d datetime | None

Datetime to format. Returns "" if None.

required
fmt str

strftime format string. Defaults to dd/mm/yyyy HH:MM.

'%d/%m/%Y %H:%M'

Returns:

Type Description
str

Formatted datetime string, or "" if d is None.

Source code in src/pinky_core/fmt.py
37
38
39
40
41
42
43
44
45
46
47
48
49
def format_datetime(d: datetime | None, fmt: str = "%d/%m/%Y %H:%M") -> str:
    """Format a datetime as a readable string with time.

    Args:
        d:   Datetime to format. Returns "" if None.
        fmt: strftime format string. Defaults to dd/mm/yyyy HH:MM.

    Returns:
        Formatted datetime string, or "" if d is None.
    """
    if d is None:
        return ""
    return d.strftime(fmt)

format_duration(seconds)

Format a duration in seconds as a human-readable string.

Examples:

45 → "45s" 125 → "2min 05s" 3661 → "1h 01min" 90000 → "1d 1h"

Parameters:

Name Type Description Default
seconds float | int | None

Duration in seconds. Returns "" if None.

required

Returns:

Type Description
str

Formatted duration string.

Source code in src/pinky_core/fmt.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def format_duration(seconds: float | int | None) -> str:
    """Format a duration in seconds as a human-readable string.

    Examples:
        45    → "45s"
        125   → "2min 05s"
        3661  → "1h 01min"
        90000 → "1d 1h"

    Args:
        seconds: Duration in seconds. Returns "" if None.

    Returns:
        Formatted duration string.
    """
    if seconds is None or (isinstance(seconds, float) and math.isnan(seconds)):
        return ""
    s = int(abs(seconds))
    sign = "-" if seconds < 0 else ""
    if s < 60:
        return f"{sign}{s}s"
    if s < 3600:
        return f"{sign}{s // 60}min {s % 60:02d}s"
    if s < 86400:
        return f"{sign}{s // 3600}h {(s % 3600) // 60:02d}min"
    days = s // 86400
    hours = (s % 86400) // 3600
    return f"{sign}{days}d {hours}h"

format_fraction(numerator, denominator)

Format a ratio as a readable fraction with percentage.

Parameters:

Name Type Description Default
numerator float | None

Numerator. Returns "" if None.

required
denominator float | None

Denominator. Returns "" if None or zero.

required

Returns:

Type Description
str

String "X / Y (Z.Z%)", or "" if inputs are invalid.

Source code in src/pinky_core/fmt.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def format_fraction(
    numerator: float | None,
    denominator: float | None,
) -> str:
    """Format a ratio as a readable fraction with percentage.

    Args:
        numerator:   Numerator. Returns "" if None.
        denominator: Denominator. Returns "" if None or zero.

    Returns:
        String "X / Y (Z.Z%)", or "" if inputs are invalid.
    """
    if (
        numerator is None
        or denominator is None
        or denominator == 0
        or (isinstance(numerator, float) and math.isnan(numerator))
        or (isinstance(denominator, float) and math.isnan(denominator))
    ):
        return ""
    pct = numerator / denominator * 100
    return f"{round(numerator)} / {round(denominator)} ({pct:.1f}%)"

format_number(num, num_type='count')

Format a number using compact notation (K, M).

Parameters:

Name Type Description Default
num float | int | None

Number to format. Returns "" if None.

required
num_type str

One of: - "count" → compact integer (K, M) - "amount" → compact amount with € suffix - "percent" → value already in % (25.0 → "25.0 %") - "percent_decimal" → decimal value x 100 (0.25 → "25.0 %")

'count'

Returns:

Type Description
str

Formatted string with appropriate suffix.

Source code in src/pinky_core/fmt.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def format_number(num: float | int | None, num_type: str = "count") -> str:
    """Format a number using compact notation (K, M).

    Args:
        num:      Number to format. Returns "" if None.
        num_type: One of:
                  - "count"           → compact integer (K, M)
                  - "amount"          → compact amount with € suffix
                  - "percent"         → value already in % (25.0 → "25.0 %")
                  - "percent_decimal" → decimal value x 100 (0.25 → "25.0 %")

    Returns:
        Formatted string with appropriate suffix.
    """
    if num is None or (isinstance(num, float) and math.isnan(num)):
        return ""
    if num_type == "percent_decimal":
        return f"{num * 100:.1f} %"
    if num_type == "percent":
        return f"{num:.1f} %"
    suffix = " €" if num_type == "amount" else ""
    sign = "-" if num < 0 else ""
    abs_num = abs(num)
    if abs_num >= 1_000_000:
        val = abs_num / 1_000_000
        return (
            f"{sign}{val:.1f} M{suffix}" if val % 1 else f"{sign}{int(val)} M{suffix}"
        )
    if abs_num >= 1_000:
        val = abs_num / 1_000
        return (
            f"{sign}{val:.1f} K{suffix}" if val % 1 else f"{sign}{int(val)} K{suffix}"
        )
    return f"{sign}{round(abs_num)}{suffix}"

format_period(period)

Format a period string as MM/YYYY.

Accepts
  • "032026" (MMYYYY) → "03/2026"
  • "2026-03" (YYYY-MM) → "03/2026"

Parameters:

Name Type Description Default
period str

Period string to format.

required

Returns:

Type Description
str

Formatted period MM/YYYY, or the original string if format is unrecognised.

Source code in src/pinky_core/fmt.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def format_period(period: str) -> str:
    """Format a period string as MM/YYYY.

    Accepts:
        - "032026" (MMYYYY) → "03/2026"
        - "2026-03" (YYYY-MM) → "03/2026"

    Args:
        period: Period string to format.

    Returns:
        Formatted period MM/YYYY, or the original string if format is unrecognised.
    """
    if len(period) == 6 and period.isdigit():
        return f"{period[:2]}/{period[2:]}"
    if len(period) == 7 and "-" in period:
        y, m = period.split("-")
        return f"{m}/{y}"
    return period

format_stars(value, max_stars=5)

Format a rating as unicode stars.

Examples:

3.5 → "★★★☆☆" 5 → "★★★★★"

Parameters:

Name Type Description Default
value float | int | None

Rating value. Returns "" if None.

required
max_stars int

Maximum number of stars. Defaults to 5.

5

Returns:

Type Description
str

String of filled and empty stars.

Source code in src/pinky_core/fmt.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def format_stars(value: float | int | None, max_stars: int = 5) -> str:
    """Format a rating as unicode stars.

    Examples:
        3.5 → "★★★☆☆"
        5   → "★★★★★"

    Args:
        value:     Rating value. Returns "" if None.
        max_stars: Maximum number of stars. Defaults to 5.

    Returns:
        String of filled and empty stars.
    """
    if value is None:
        return ""
    filled = min(round(value), max_stars)
    return "★" * filled + "☆" * (max_stars - filled)

format_trend(current, previous)

Format a trend with a directional arrow.

Examples:

(120, 100) → "↑ +20.0%" (80, 100) → "↓ -20.0%" (100, 100) → "→ 0.0%"

Parameters:

Name Type Description Default
current float | None

Current value. Returns "" if None.

required
previous float | None

Previous value. Returns "" if None or zero.

required

Returns:

Type Description
str

Trend string with arrow and percentage change.

Source code in src/pinky_core/fmt.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def format_trend(current: float | None, previous: float | None) -> str:
    """Format a trend with a directional arrow.

    Examples:
        (120, 100) → "↑ +20.0%"
        (80, 100)  → "↓ -20.0%"
        (100, 100) → "→ 0.0%"

    Args:
        current:  Current value. Returns "" if None.
        previous: Previous value. Returns "" if None or zero.

    Returns:
        Trend string with arrow and percentage change.
    """
    if (
        current is None
        or previous is None
        or previous == 0
        or (isinstance(current, float) and math.isnan(current))
        or (isinstance(previous, float) and math.isnan(previous))
    ):
        return ""
    delta_pct = (current - previous) / abs(previous) * 100
    if delta_pct > 0:
        return f"↑ +{delta_pct:.1f}%"
    if delta_pct < 0:
        return f"↓ {delta_pct:.1f}%"
    return "→ 0.0%"

iso3_to_iso2(code)

Convert an ISO 3166-1 alpha-3 country code to alpha-2.

Returns the input unchanged if it is already alpha-2 or unknown.

Examples:

"FRA" → "FR" "USA" → "US" "FR" → "FR"

Parameters:

Name Type Description Default
code str

ISO 3166-1 alpha-2 or alpha-3 country code (case-insensitive).

required

Returns:

Type Description
str

ISO 3166-1 alpha-2 country code.

Source code in src/pinky_core/fmt.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def iso3_to_iso2(code: str) -> str:
    """Convert an ISO 3166-1 alpha-3 country code to alpha-2.

    Returns the input unchanged if it is already alpha-2 or unknown.

    Examples:
        "FRA" → "FR"
        "USA" → "US"
        "FR"  → "FR"

    Args:
        code: ISO 3166-1 alpha-2 or alpha-3 country code (case-insensitive).

    Returns:
        ISO 3166-1 alpha-2 country code.
    """
    upper = code.strip().upper()
    return _ISO3_TO_ISO2.get(upper, upper)

normalize_city_fr(city)

Normalize a French city name to its ADP/AFNOR abbreviated form.

Applies :func:normalize_text then substitutes SAINTST and SAINTESTE (whole words only, not inside longer words).

Examples:

"Saint-Étienne" → "ST ETIENNE" "Sainte-Marie" → "STE MARIE" "Villesaint" → "VILLESAINT" (not a whole word, unchanged)

Parameters:

Name Type Description Default
city str | None

Raw city name.

required

Returns:

Type Description
str | None

Normalized city string, or None if input is None or blank.

Source code in src/pinky_core/fmt.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def normalize_city_fr(city: str | None) -> str | None:
    """Normalize a French city name to its ADP/AFNOR abbreviated form.

    Applies :func:`normalize_text` then substitutes ``SAINT`` → ``ST`` and
    ``SAINTE`` → ``STE`` (whole words only, not inside longer words).

    Examples:
        "Saint-Étienne"   → "ST ETIENNE"
        "Sainte-Marie"    → "STE MARIE"
        "Villesaint"      → "VILLESAINT"  (not a whole word, unchanged)

    Args:
        city: Raw city name.

    Returns:
        Normalized city string, or ``None`` if input is ``None`` or blank.
    """
    normalized = normalize_text(city)
    if not normalized:
        return None
    normalized = re.sub(r"\bSAINTE\b", "STE", normalized)
    normalized = re.sub(r"\bSAINT\b", "ST", normalized)
    return normalized

normalize_text(text)

Normalize a string for postal/administrative use.

Applies unidecode transliteration, uppercases, then replaces any run of non-alphanumeric characters with a single space. Returns None for blank input.

Equivalent to the udf_standardize pattern used in ADP/Workday flows.

Examples:

"Résidence de l'Étoile" → "RESIDENCE DE L ETOILE" "Saint-Étienne" → "SAINT ETIENNE"

Parameters:

Name Type Description Default
text str | None

Raw string to normalize.

required

Returns:

Type Description
str | None

Normalized string, or None if input is None or blank.

Source code in src/pinky_core/fmt.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def normalize_text(text: str | None) -> str | None:
    """Normalize a string for postal/administrative use.

    Applies unidecode transliteration, uppercases, then replaces any run of
    non-alphanumeric characters with a single space.  Returns ``None`` for
    blank input.

    Equivalent to the ``udf_standardize`` pattern used in ADP/Workday flows.

    Examples:
        "Résidence de l'Étoile" → "RESIDENCE DE L ETOILE"
        "Saint-Étienne"          → "SAINT ETIENNE"

    Args:
        text: Raw string to normalize.

    Returns:
        Normalized string, or ``None`` if input is ``None`` or blank.
    """
    from unidecode import unidecode

    if not text or not text.strip():
        return None
    normalized = re.sub(r"[^A-Z0-9 ]+", " ", unidecode(text).upper())
    return re.sub(r" +", " ", normalized).strip() or None

parse_address(address, country_code='FR', zip_code=None, city=None)

Parse a postal address into structured components.

Parameters:

Name Type Description Default
address str

Raw address string. Can be the street line only ("12 BIS RUE DES LILAS") or a full address including postal code and city ("12 BIS RUE DES LILAS 75019 PARIS"). When the full address is passed and zip_code / city are omitted, they are extracted automatically (FR only).

required
country_code str

ISO 3166-1 alpha-2 ("FR", "US") or alpha-3 ("FRA", "USA"). Case-insensitive. Countries without a dedicated parser return AddressComponents(raw=address).

'FR'
zip_code str | None

Postal code from the source data. Overrides extraction from address.

None
city str | None

City name from the source data. Overrides extraction from address.

None

Returns:

Type Description
AddressComponents

AddressComponents with parsed fields. raw is always set to

AddressComponents

the original input. afnor contains the NF Z10-011 normalised

AddressComponents

street line for FR addresses.

Note

US parsing requires the optional usaddress package::

pip install pinky-core[address]
Source code in src/pinky_core/fmt.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def parse_address(
    address: str,
    country_code: str = "FR",
    zip_code: str | None = None,
    city: str | None = None,
) -> AddressComponents:
    """Parse a postal address into structured components.

    Args:
        address:      Raw address string.  Can be the street line only
                      (``"12 BIS RUE DES LILAS"``) or a full address including
                      postal code and city (``"12 BIS RUE DES LILAS 75019 PARIS"``).
                      When the full address is passed and ``zip_code`` / ``city``
                      are omitted, they are extracted automatically (FR only).
        country_code: ISO 3166-1 alpha-2 (``"FR"``, ``"US"``) or alpha-3
                      (``"FRA"``, ``"USA"``). Case-insensitive.
                      Countries without a dedicated parser return
                      ``AddressComponents(raw=address)``.
        zip_code:     Postal code from the source data.  Overrides extraction
                      from ``address``.
        city:         City name from the source data.  Overrides extraction
                      from ``address``.

    Returns:
        ``AddressComponents`` with parsed fields.  ``raw`` is always set to
        the original input.  ``afnor`` contains the NF Z10-011 normalised
        street line for FR addresses.

    Note:
        US parsing requires the optional ``usaddress`` package::

            pip install pinky-core[address]
    """
    if not address or not address.strip():
        return AddressComponents(zip_code=zip_code, city=city, raw=address or None)

    code = country_code.strip().upper()
    if len(code) == 3:
        code = _ISO3_TO_ISO2.get(code, code)

    parser = _COUNTRY_PARSERS.get(code)
    if parser:
        try:
            return parser(address, zip_code=zip_code, city=city)
        except Exception:
            return AddressComponents(zip_code=zip_code, city=city, raw=address)

    return AddressComponents(zip_code=zip_code, city=city, raw=address)

period_to_date(period)

Convert a period string to a date object (first day of the month).

Accepts
  • "032026" (MMYYYY) → date(2026, 3, 1)
  • "2026-03" (YYYY-MM) → date(2026, 3, 1)

Parameters:

Name Type Description Default
period str

Period string to convert.

required

Returns:

Type Description
date

Date of the first day of the month.

Raises:

Type Description
ValueError

If the format is not recognised.

Source code in src/pinky_core/fmt.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def period_to_date(period: str) -> date:
    """Convert a period string to a date object (first day of the month).

    Accepts:
        - "032026" (MMYYYY) → date(2026, 3, 1)
        - "2026-03" (YYYY-MM) → date(2026, 3, 1)

    Args:
        period: Period string to convert.

    Returns:
        Date of the first day of the month.

    Raises:
        ValueError: If the format is not recognised.
    """
    if len(period) == 6 and period.isdigit():
        return date(int(period[2:]), int(period[:2]), 1)
    if len(period) == 7 and "-" in period:
        y, m = period.split("-")
        return date(int(y), int(m), 1)
    raise ValueError(f"Unrecognised period format: {period!r}")

to_camel_case(name)

Convert UPPER_SNAKE_CASE or snake_case to camelCase.

Useful for building Snowflake OBJECT keys that follow JSON/camelCase conventions (e.g. UDF return dicts consumed by downstream SQL).

Examples:

"is_valid_email" → "isValidEmail" "COUNTRY_CODE" → "countryCode" "phone" → "phone"

Parameters:

Name Type Description Default
name str

Snake-case or upper-snake-case string to convert.

required

Returns:

Type Description
str

camelCase string.

Source code in src/pinky_core/fmt.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def to_camel_case(name: str) -> str:
    """Convert UPPER_SNAKE_CASE or snake_case to camelCase.

    Useful for building Snowflake OBJECT keys that follow JSON/camelCase
    conventions (e.g. UDF return dicts consumed by downstream SQL).

    Examples:
        "is_valid_email" → "isValidEmail"
        "COUNTRY_CODE"   → "countryCode"
        "phone"          → "phone"

    Args:
        name: Snake-case or upper-snake-case string to convert.

    Returns:
        camelCase string.
    """
    parts = name.lower().split("_")
    return parts[0] + "".join(p.capitalize() for p in parts[1:])

to_upper_snake_case(name)

Convert a string to UPPER_SNAKE_CASE for Snowflake identifiers.

Uses unidecode to transliterate accented and non-ASCII characters, then collapses any run of non-alphanumeric characters to a single _.

Examples:

"NAF 2025\nsous-classes" → "NAF_2025_SOUS_CLASSES" "Intitulés" → "INTITULES" "first name" → "FIRST_NAME" "Ñoño" → "NONO"

Parameters:

Name Type Description Default
name str

String to convert.

required

Returns:

Type Description
str

UPPER_SNAKE_CASE string safe for use as a Snowflake identifier.

Source code in src/pinky_core/fmt.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def to_upper_snake_case(name: str) -> str:
    """Convert a string to UPPER_SNAKE_CASE for Snowflake identifiers.

    Uses ``unidecode`` to transliterate accented and non-ASCII characters,
    then collapses any run of non-alphanumeric characters to a single ``_``.

    Examples:
        "NAF 2025\\nsous-classes" → "NAF_2025_SOUS_CLASSES"
        "Intitulés"               → "INTITULES"
        "first name"              → "FIRST_NAME"
        "Ñoño"                    → "NONO"

    Args:
        name: String to convert.

    Returns:
        UPPER_SNAKE_CASE string safe for use as a Snowflake identifier.
    """
    from unidecode import unidecode

    name = unidecode(name)
    name = re.sub(r"[^a-zA-Z0-9]+", "_", name)
    return name.strip("_").upper()