or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-locales.mddate-time-formatting.mdindex.mdmessage-catalogs.mdnumber-currency-formatting.mdplural-language-data.mdunits-utilities.md

index.mddocs/

0

# Babel

1

2

A comprehensive Python internationalization and localization library that provides an integrated collection of utilities for internationalizing and localizing Python applications. Babel consists of two major components: tools for building and working with gettext message catalogs for translating user interfaces, and a Python interface to the CLDR (Common Locale Data Repository) providing access to various locale display names, localized number and date formatting, currency symbols, and other locale-specific data.

3

4

## Package Information

5

6

- **Package Name**: babel

7

- **Language**: Python

8

- **Installation**: `pip install babel`

9

10

## Core Imports

11

12

```python

13

import babel

14

from babel import Locale, UnknownLocaleError

15

```

16

17

For specific functionality:

18

19

```python

20

from babel.core import Locale, default_locale, negotiate_locale, parse_locale

21

from babel.dates import format_date, format_datetime, format_time

22

from babel.numbers import format_decimal, format_currency, format_percent

23

from babel.messages import Catalog, Message

24

```

25

26

## Basic Usage

27

28

```python

29

from babel import Locale

30

from babel.dates import format_date, format_datetime

31

from babel.numbers import format_decimal, format_currency

32

import datetime

33

34

# Create locale objects

35

locale = Locale('en_US')

36

french_locale = Locale('fr_FR')

37

38

# Format dates according to locale

39

date = datetime.date(2023, 12, 25)

40

formatted_date = format_date(date, locale=locale) # "Dec 25, 2023"

41

formatted_date_fr = format_date(date, locale=french_locale) # "25 déc. 2023"

42

43

# Format numbers and currencies

44

number = 1234.56

45

formatted_number = format_decimal(number, locale=locale) # "1,234.56"

46

formatted_currency = format_currency(number, 'USD', locale=locale) # "$1,234.56"

47

48

# Access locale information

49

print(locale.get_display_name()) # "English (United States)"

50

print(locale.get_language_name()) # "English"

51

print(locale.get_territory_name()) # "United States"

52

```

53

54

## Architecture

55

56

Babel's architecture centers around locale objects and formatting functions that leverage CLDR data:

57

58

- **Locale**: Central class providing access to locale-specific data and formatting rules

59

- **CLDR Integration**: Comprehensive locale data repository providing culturally appropriate formatting

60

- **Formatting Functions**: Specialized functions for dates, numbers, currencies, and units

61

- **Message Catalogs**: Complete gettext-compatible translation management system

62

- **Extensible Design**: Modular structure allowing selective imports and customization

63

64

This design enables Babel to serve as the primary internationalization library for Python applications, supporting both simple locale-aware formatting tasks and complex multilingual application development workflows.

65

66

## Capabilities

67

68

### Core Locale Management

69

70

Fundamental locale operations including locale creation, parsing, negotiation, and access to locale-specific display information and formatting rules.

71

72

```python { .api }

73

class Locale:

74

def __init__(self, language, territory=None, script=None, variant=None, modifier=None): ...

75

@classmethod

76

def parse(cls, identifier, sep='_', resolve_likely_subtags=True): ...

77

def get_display_name(self, locale=None): ...

78

def get_language_name(self, locale=None): ...

79

80

def default_locale(category=None, aliases=None): ...

81

def negotiate_locale(preferred, available, sep='_', aliases=None): ...

82

def parse_locale(identifier, sep='_'): ...

83

```

84

85

[Core Locale Management](./core-locales.md)

86

87

### Date and Time Formatting

88

89

Comprehensive date, time, and datetime formatting with locale-aware patterns, timezone support, and flexible formatting options including skeleton-based formatting and relative time display.

90

91

```python { .api }

92

def format_date(date, format='medium', locale=default_locale()): ...

93

def format_datetime(datetime, format='medium', tzinfo=None, locale=default_locale()): ...

94

def format_time(time, format='medium', tzinfo=None, locale=default_locale()): ...

95

def format_timedelta(delta, granularity='second', threshold=0.85, add_direction=False, format='long', locale=default_locale()): ...

96

```

97

98

[Date and Time Formatting](./date-time-formatting.md)

99

100

### Number and Currency Formatting

101

102

Locale-aware number, decimal, currency, and percentage formatting with support for different numbering systems, compact notation, and precision control.

103

104

```python { .api }

105

def format_decimal(number, format=None, locale=default_locale(), numbering_system="latn"): ...

106

def format_currency(number, currency, format=None, locale=default_locale(), currency_digits=True, format_type='standard'): ...

107

def format_percent(number, format=None, locale=default_locale(), numbering_system="latn"): ...

108

def format_scientific(number, format=None, locale=default_locale(), numbering_system="latn"): ...

109

```

110

111

[Number and Currency Formatting](./number-currency-formatting.md)

112

113

### Message Catalog Management

114

115

Complete gettext-compatible message catalog system for managing translatable strings, including catalog creation, message extraction, PO/MO file handling, and translation management.

116

117

```python { .api }

118

class Catalog:

119

def __init__(self, locale=None, domain=None, **kwargs): ...

120

def add(self, id, string=None, locations=(), flags=(), auto_comments=(), user_comments=()): ...

121

def get(self, id, context=None): ...

122

123

class Message:

124

def __init__(self, id, string='', locations=(), flags=(), auto_comments=(), user_comments=()): ...

125

```

126

127

[Message Catalog Management](./message-catalogs.md)

128

129

### Plural Rules and Language Data

130

131

Plural rule handling for different languages, language territory information, and list formatting according to locale conventions.

132

133

```python { .api }

134

class PluralRule:

135

def __init__(self, rules): ...

136

def __call__(self, n): ...

137

138

def get_official_languages(territory, regional=False, de_facto=False): ...

139

def format_list(lst, style='standard', locale=default_locale()): ...

140

```

141

142

[Plural Rules and Language Data](./plural-language-data.md)

143

144

### Units and Utilities

145

146

Unit formatting for measurements, utility functions for text processing and pattern matching, and support classes for translation management.

147

148

```python { .api }

149

def format_unit(value, measurement_unit, length='long', format=None, locale=default_locale()): ...

150

def format_compound_unit(numerator_value, numerator_unit, denominator_value, denominator_unit, length='long', format=None, locale=default_locale()): ...

151

152

class Format:

153

def __init__(self, locale, tzinfo=None, numbering_system="latn"): ...

154

def date(self, date=None, format='medium'): ...

155

def currency(self, number, currency): ...

156

```

157

158

[Units and Utilities](./units-utilities.md)

159

160

## Exception Classes

161

162

```python { .api }

163

class UnknownLocaleError(Exception):

164

"""Raised when an unknown locale identifier is used."""

165

166

class UnknownCurrencyError(Exception):

167

"""Raised when an unknown currency code is used."""

168

169

class UnknownUnitError(ValueError):

170

"""Raised when an unknown unit of measurement is used."""

171

172

class UnsupportedNumberingSystemError(Exception):

173

"""Raised when an unsupported numbering system is used."""

174

175

class UnknownCurrencyFormatError(KeyError):

176

"""Raised when an unknown currency format is requested."""

177

178

class NumberFormatError(ValueError):

179

"""Raised when number formatting fails."""

180

181

class ParseError(ValueError):

182

"""Raised when date/time parsing fails."""

183

184

class RuleError(Exception):

185

"""Raised when plural rule parsing or evaluation fails."""

186

187

class TranslationError(Exception):

188

"""Raised for translation-related errors."""

189

190

class PoFileError(Exception):

191

"""Raised when PO file parsing fails."""

192

```