Internationalization utilities for Python providing locale data, date/time/number formatting, and message catalog management
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Unit formatting for measurements, utility functions for text processing and pattern matching, and support classes for translation management. This module provides additional functionality that complements Babel's core internationalization features.
Format measurement values with units according to locale conventions.
def format_unit(value, measurement_unit, length='long', format=None,
locale=default_locale(), numbering_system="latn"):
"""
Format a value with unit according to locale conventions.
Args:
value (int|float|Decimal): Numeric value to format
measurement_unit (str): Unit identifier (e.g., 'meter', 'kilogram', 'second')
length (str): Format length ('long', 'short', 'narrow')
format (str, optional): Number format pattern
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Formatted value with unit
Raises:
UnknownUnitError: If unit is not recognized
"""
def format_compound_unit(numerator_value, numerator_unit, denominator_value,
denominator_unit, length='long', format=None,
locale=default_locale(), numbering_system="latn"):
"""
Format compound unit (e.g., "kilometers per hour").
Args:
numerator_value (int|float|Decimal): Numerator value
numerator_unit (str): Numerator unit identifier
denominator_value (int|float|Decimal): Denominator value
denominator_unit (str): Denominator unit identifier
length (str): Format length ('long', 'short', 'narrow')
format (str, optional): Number format pattern
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Formatted compound unit
"""
def get_unit_name(measurement_unit, length='long', locale=default_locale()):
"""
Get display name for a measurement unit.
Args:
measurement_unit (str): Unit identifier
length (str): Format length ('long', 'short', 'narrow')
locale (Locale|str): Target locale
Returns:
str|None: Unit display name or None if not found
"""Usage example:
from babel.units import format_unit, format_compound_unit, get_unit_name
# Basic unit formatting
print(format_unit(5, 'meter', locale='en_US')) # "5 meters"
print(format_unit(5, 'meter', locale='fr_FR')) # "5 mètres"
print(format_unit(1, 'meter', locale='en_US')) # "1 meter"
# Different lengths
print(format_unit(10, 'kilogram', length='long', locale='en_US')) # "10 kilograms"
print(format_unit(10, 'kilogram', length='short', locale='en_US')) # "10 kg"
print(format_unit(10, 'kilogram', length='narrow', locale='en_US')) # "10kg"
# Compound units
print(format_compound_unit(60, 'kilometer', 1, 'hour', locale='en_US')) # "60 kilometers per hour"
print(format_compound_unit(60, 'kilometer', 1, 'hour', length='short', locale='en_US')) # "60 km/h"
# Unit names
print(get_unit_name('meter', locale='en_US')) # "meter"
print(get_unit_name('meter', locale='fr_FR')) # "mètre"Convenience class that provides locale-bound formatting methods.
class Format:
"""
Wrapper providing date/number formatting bound to a specific locale.
"""
def __init__(self, locale, tzinfo=None, numbering_system="latn"):
"""
Initialize formatter for specific locale.
Args:
locale (Locale|str): Target locale
tzinfo (datetime.tzinfo, optional): Default timezone
numbering_system (str): Default numbering system
"""
def date(self, date=None, format='medium'):
"""
Format a date using this formatter's locale.
Args:
date (datetime.date, optional): Date to format (default: today)
format (str): Format style
Returns:
str: Formatted date
"""
def datetime(self, datetime=None, format='medium'):
"""
Format a datetime using this formatter's locale.
Args:
datetime (datetime.datetime, optional): Datetime to format (default: now)
format (str): Format style
Returns:
str: Formatted datetime
"""
def time(self, time=None, format='medium'):
"""
Format a time using this formatter's locale.
Args:
time (datetime.time, optional): Time to format (default: now)
format (str): Format style
Returns:
str: Formatted time
"""
def timedelta(self, delta, granularity="second", threshold=0.85,
format="long", add_direction=False):
"""
Format a timedelta using this formatter's locale.
Args:
delta (datetime.timedelta): Time difference to format
granularity (str): Smallest unit to display
threshold (float): Threshold for larger units
format (str): Format style
add_direction (bool): Whether to add directional words
Returns:
str: Formatted timedelta
"""
def number(self, number):
"""
Format a number using this formatter's locale.
Args:
number (int|float|Decimal): Number to format
Returns:
str: Formatted number
"""
def decimal(self, number, format=None):
"""
Format a decimal using this formatter's locale.
Args:
number (int|float|Decimal): Number to format
format (str, optional): Number format pattern
Returns:
str: Formatted decimal
"""
def compact_decimal(self, number, format_type='short', fraction_digits=0):
"""
Format a decimal in compact notation.
Args:
number (int|float|Decimal): Number to format
format_type (str): Format type ('short', 'long')
fraction_digits (int): Number of fraction digits
Returns:
str: Compact formatted decimal
"""
def currency(self, number, currency):
"""
Format a currency amount using this formatter's locale.
Args:
number (int|float|Decimal): Amount to format
currency (str): Currency code
Returns:
str: Formatted currency
"""
def compact_currency(self, number, currency, format_type='short', fraction_digits=0):
"""
Format a currency amount in compact notation.
Args:
number (int|float|Decimal): Amount to format
currency (str): Currency code
format_type (str): Format type ('short', 'long')
fraction_digits (int): Number of fraction digits
Returns:
str: Compact formatted currency
"""
def percent(self, number, format=None):
"""
Format a percentage using this formatter's locale.
Args:
number (int|float|Decimal): Number to format as percentage
format (str, optional): Percent format pattern
Returns:
str: Formatted percentage
"""
def scientific(self, number):
"""
Format a number in scientific notation.
Args:
number (int|float|Decimal): Number to format
Returns:
str: Number in scientific notation
"""Usage example:
from babel.support import Format
from babel import Locale
import datetime
# Create formatter for specific locale
formatter = Format(Locale('fr_FR'))
# Use formatter methods
now = datetime.datetime.now()
print(formatter.date(now.date())) # French date format
print(formatter.currency(1234.56, 'EUR')) # "1 234,56 €"
print(formatter.percent(0.1234)) # "12 %"Proxy object that delays evaluation of expensive operations until actually needed.
class LazyProxy:
"""
Proxy object that delays evaluation until the value is actually used.
"""
def __init__(self, func, *args, enable_cache=True, **kwargs):
"""
Initialize lazy proxy.
Args:
func (callable): Function to call for evaluation
*args: Arguments to pass to function
enable_cache (bool): Whether to cache the result
**kwargs: Keyword arguments to pass to function
"""Usage example:
from babel.support import LazyProxy
def expensive_operation():
print("Computing expensive result...")
return "Result"
# Create lazy proxy
lazy_result = LazyProxy(expensive_operation)
# Function not called yet
print("Proxy created")
# Function called on first access
print(lazy_result) # "Computing expensive result..." then "Result"
print(lazy_result) # Just "Result" (cached)Extended translation classes with additional functionality.
class NullTranslations:
"""
Base translation class without catalog (fallback behavior).
Inherits from gettext.NullTranslations with Babel extensions.
"""
def dgettext(self, domain, message):
"""Get translation for message in domain."""
def pgettext(self, context, message):
"""Get translation for message with context."""
def dpgettext(self, domain, context, message):
"""Get translation for message with domain and context."""
class Translations(NullTranslations):
"""
Extended translation catalog class with Babel features.
Inherits from both NullTranslations and gettext.GNUTranslations.
"""
@classmethod
def load(cls, dirname=None, locales=None, domain=None):
"""
Load translations from directory structure.
Args:
dirname (str, optional): Directory containing translations
locales (list, optional): List of locale identifiers to load
domain (str, optional): Message domain to load
Returns:
Translations: Loaded translation object
"""
def add(self, translations, merge=True):
"""
Add translations from another catalog.
Args:
translations (Translations): Translation catalog to add
merge (bool): Whether to merge conflicting entries
"""
def merge(self, translations):
"""
Merge translations from another catalog.
Args:
translations (Translations): Translation catalog to merge
"""General utility functions for text processing and file handling.
def distinct(iterable):
"""
Yield distinct items from iterable, preserving order.
Args:
iterable: Input sequence
Returns:
Generator: Distinct items in original order
"""
def parse_encoding(fp):
"""
Parse character encoding from Python file magic comment.
Args:
fp (IO[bytes]): File object to read from
Returns:
str|None: Detected encoding or None
"""
def parse_future_flags(fp, encoding='utf-8'):
"""
Parse __future__ import flags from Python code.
Args:
fp (IO[bytes]): File object to read from
encoding (str): Character encoding
Returns:
int: Combined future flags
"""
def pathmatch(pattern, filename):
"""
Extended pathname pattern matching with ** support.
Args:
pattern (str): Pattern with wildcards (* and **)
filename (str): Filename to match against pattern
Returns:
bool: True if filename matches pattern
"""Usage example:
from babel.util import distinct, pathmatch
# Remove duplicates while preserving order
items = [1, 2, 2, 3, 1, 4]
unique_items = list(distinct(items)) # [1, 2, 3, 4]
# Pattern matching
print(pathmatch('src/**/*.py', 'src/module/file.py')) # True
print(pathmatch('*.txt', 'document.txt')) # True
print(pathmatch('test_*.py', 'test_parser.py')) # TrueEnhanced text wrapping that handles special cases.
class TextWrapper:
"""
Enhanced text wrapper that handles filenames with spaces.
Inherits from textwrap.TextWrapper with improvements.
"""
def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
"""
Wrap text preserving filenames with spaces (deprecated).
Args:
text (str): Text to wrap
width (int): Maximum line width
initial_indent (str): Initial line indent
subsequent_indent (str): Subsequent line indent
Returns:
list[str]: List of wrapped lines
"""Fixed-offset timezone implementation and timezone constants.
class FixedOffsetTimezone:
"""
Timezone with fixed offset from UTC.
Inherits from datetime.tzinfo.
"""
def __init__(self, offset, name=None):
"""
Initialize fixed offset timezone.
Args:
offset (datetime.timedelta): UTC offset
name (str, optional): Timezone name
"""
# Timezone constants
UTC: datetime.tzinfo
"""UTC timezone object (re-exported from babel.dates)"""
LOCALTZ: datetime.tzinfo
"""Local timezone object (re-exported from babel.dates)"""Usage example:
from babel.util import FixedOffsetTimezone, UTC
import datetime
# Create fixed offset timezone
est = FixedOffsetTimezone(datetime.timedelta(hours=-5), 'EST')
# Use with datetime
dt = datetime.datetime(2023, 12, 25, 12, 0, tzinfo=est)
utc_dt = dt.astimezone(UTC)class UnknownUnitError(Exception):
"""Raised when an unknown unit identifier is used."""Various constants used throughout Babel utilities are re-exported here for convenience, including timezone objects and default values.
Install with Tessl CLI
npx tessl i tessl/pypi-babel