Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import Optional
from .form_address_data import COUNTRIES ← this capability’s own data, compiled from data/countries.json into the same file by fune build
from .form_address_types import AddressFormat
# The UK and the Crown Dependencies share Royal Mail's postcode format.
UK_FAMILY = ("GB", "GG", "JE", "IM")
_SPACE = " \t\n\r\f\v"
def trim_ascii(value: str) -> str:
"""Leading and trailing ASCII whitespace removed, the same in every language."""
return value.strip(_SPACE)
def upper_ascii(value: str) -> str:
"""ASCII letters upper-cased; everything else as it is (str.upper() would
also change "ß" and other scripts)."""
return "".join(chr(ord(c) - 32) if "a" <= c <= "z" else c for c in value)
def is_uk_family(code: str) -> bool:
"""Whether a country code (already upper case) uses the UK postcode format."""
return code in UK_FAMILY
def lookup_country(country: str):
"""The country's row, by its code as typed (trimmed, any case), or None."""
code = upper_ascii(trim_ascii(country))
for row in COUNTRIES:
if row.code == code:
return row
return None
def address_format(country: str) -> AddressFormat:
"""How an address form for a country labels and checks its fields."""
row = lookup_country(country)
if row is None:
raise ValueError('unknown country "%s": give an ISO 3166-1 alpha-2 code, such as GB, US or DE' % country)
return AddressFormat(
country=row.code,
name=row.name,
uk=is_uk_family(row.code),
postcode_label=row.postcode_label,
postcode_required=row.postcode_required,
postcode_example=row.postcode_example,
region_label=row.region_label,
)