1BABEL(1) Babel BABEL(1)
2
3
4
6 babel - Babel Documentation
7
8 Babel is an integrated collection of utilities that assist in interna‐
9 tionalizing and localizing Python applications, with an emphasis on
10 web-based applications.
11
13 The user documentation explains some core concept of the library and
14 gives some information about how it can be used.
15
16 Introduction
17 The functionality Babel provides for internationalization (I18n) and
18 localization (L10N) can be separated into two different aspects:
19
20 • tools to build and work with gettext message catalogs, and
21
22 • a Python interface to the CLDR (Common Locale Data Repository),
23 providing access to various locale display names, localized number
24 and date formatting, etc.
25
26 Message Catalogs
27 While the Python standard library includes a gettext module that en‐
28 ables applications to use message catalogs, it requires developers to
29 build these catalogs using GNU tools such as xgettext, msgmerge, and
30 msgfmt. And while xgettext does have support for extracting messages
31 from Python files, it does not know how to deal with other kinds of
32 files commonly found in Python web-applications, such as templates, nor
33 does it provide an easy extensibility mechanism to add such support.
34
35 Babel addresses this by providing a framework where various extraction
36 methods can be plugged in to a larger message extraction framework, and
37 also removes the dependency on the GNU gettext tools for common tasks,
38 as these aren’t necessarily available on all platforms. See Working
39 with Message Catalogs for details on this aspect of Babel.
40
41 Locale Data
42 Furthermore, while the Python standard library does include support for
43 basic localization with respect to the formatting of numbers and dates
44 (the locale module, among others), this support is based on the assump‐
45 tion that there will be only one specific locale used per process (at
46 least simultaneously.) Also, it doesn’t provide access to other kinds
47 of locale data, such as the localized names of countries, languages, or
48 time-zones, which are frequently needed in web-based applications.
49
50 For these requirements, Babel includes data extracted from the Common
51 Locale Data Repository (CLDR), and provides a number of convenient
52 methods for accessing and using this data. See Locale Data, Date and
53 Time, and Number Formatting for more information on this aspect of Ba‐
54 bel.
55
56 Installation
57 Babel is distributed as a standard Python package fully set up with all
58 the dependencies it needs. It primarily depends on the excellent pytz
59 library for timezone handling. To install it you can use pip.
60
61 virtualenv
62 Virtualenv is probably what you want to use during development, and if
63 you have shell access to your production machines, you’ll probably want
64 to use it there, too. Use pip to install it:
65
66 $ sudo pip install virtualenv
67
68 If you’re on Windows, run it in a command-prompt window with adminis‐
69 trator privileges, and leave out sudo.
70
71 Once you have virtualenv installed, just fire up a shell and create
72 your own environment. I usually create a project folder and a venv
73 folder within:
74
75 $ mkdir myproject
76 $ cd myproject
77 $ virtualenv venv
78 New python executable in venv/bin/python
79 Installing distribute............done.
80
81 Now, whenever you want to work on a project, you only have to activate
82 the corresponding environment. On OS X and Linux, do the following:
83
84 $ . venv/bin/activate
85
86 If you are a Windows user, the following command is for you:
87
88 $ venv\scripts\activate
89
90 Either way, you should now be using your virtualenv (notice how the
91 prompt of your shell has changed to show the active environment).
92
93 Now you can just enter the following command to get Babel installed in
94 your virtualenv:
95
96 $ pip install Babel
97
98 A few seconds later and you are good to go.
99
100 System-Wide Installation
101 This is possible as well, though I do not recommend it. Just run pip
102 with root privileges:
103
104 $ sudo pip install Babel
105
106 (On Windows systems, run it in a command-prompt window with administra‐
107 tor privileges, and leave out sudo.)
108
109 Living on the Edge
110 If you want to work with the latest version of Babel, you will need to
111 use a git checkout.
112
113 Get the git checkout in a new virtualenv and run in development mode:
114
115 $ git clone https://github.com/python-babel/babel
116 Initialized empty Git repository in ~/dev/babel/.git/
117 $ cd babel
118 $ virtualenv venv
119 New python executable in venv/bin/python
120 Installing distribute............done.
121 $ . venv/bin/activate
122 $ pip install pytz
123 $ python setup.py import_cldr
124 $ pip install --editable .
125 ...
126 Finished processing dependencies for Babel
127
128 Make sure to not forget about the pip install pytz and import_cldr
129 steps because otherwise you will be missing the locale data. The cus‐
130 tom setup command will download the most appropriate CLDR release from
131 the official website and convert it for Babel but will not work without
132 pytz.
133
134 This will pull also in the dependencies and activate the git head as
135 the current version inside the virtualenv. Then all you have to do is
136 run git pull origin to update to the latest version. If the CLDR data
137 changes you will have to re-run python setup.py import_cldr.
138
139 Locale Data
140 While message catalogs allow you to localize any messages in your ap‐
141 plication, there are a number of strings that are used in many applica‐
142 tions for which translations are readily available.
143
144 Imagine for example you have a list of countries that users can choose
145 from, and you’d like to display the names of those countries in the
146 language the user prefers. Instead of translating all those country
147 names yourself in your application, you can make use of the transla‐
148 tions provided by the locale data included with Babel, which is based
149 on the Common Locale Data Repository (CLDR) developed and maintained by
150 the Unicode Consortium.
151
152 The Locale Class
153 You normally access such locale data through the Locale class provided
154 by Babel:
155
156 >>> from babel import Locale
157 >>> locale = Locale('en', 'US')
158 >>> locale.territories['US']
159 u'United States'
160 >>> locale = Locale('es', 'MX')
161 >>> locale.territories['US']
162 u'Estados Unidos'
163
164 In addition to country/territory names, the locale data also provides
165 access to names of languages, scripts, variants, time zones, and more.
166 Some of the data is closely related to number and date formatting.
167
168 Most of the corresponding Locale properties return dictionaries, where
169 the key is a code such as the ISO country and language codes. Consult
170 the API documentation for references to the relevant specifications.
171
172 Likely Subtags
173 When dealing with locales you can run into the situation where a locale
174 tag is not fully descriptive. For instance people commonly refer to
175 zh_TW but that identifier does not resolve to a locale that the CLDR
176 covers. Babel’s locale identifier parser in that case will attempt to
177 resolve the most likely subtag to end up with the intended locale:
178
179 >>> from babel import Locale
180 >>> Locale.parse('zh_TW')
181 Locale('zh', territory='TW', script='Hant')
182
183 This can also be used to find the most appropriate locale for a terri‐
184 tory. In that case the territory code needs to be prefixed with und
185 (unknown language identifier):
186
187 >>> Locale.parse('und_AZ')
188 Locale('az', territory='AZ', script='Latn')
189 >>> Locale.parse('und_DE')
190 Locale('de', territory='DE')
191
192 Babel currently cannot deal with fuzzy locales (a locale not fully
193 backed by data files) so we only accept locales that are fully backed
194 by CLDR data. This will change in the future, but for the time being
195 this restriction is in place.
196
197 Locale Display Names
198 Locales itself can be used to describe the locale itself or other lo‐
199 cales. This mainly means that given a locale object you can ask it for
200 its canonical display name, the name of the language and other things.
201 Since the locales cross-reference each other you can ask for locale
202 names in any language supported by the CLDR:
203
204 >>> l = Locale.parse('de_DE')
205 >>> l.get_display_name('en_US')
206 u'German (Germany)'
207 >>> l.get_display_name('fr_FR')
208 u'allemand (Allemagne)'
209
210 Display names include all the information to uniquely identify a locale
211 (language, territory, script and variant) which is often not what you
212 want. You can also ask for the information in parts:
213
214 >>> l.get_language_name('de_DE')
215 u'Deutsch'
216 >>> l.get_language_name('it_IT')
217 u'tedesco'
218 >>> l.get_territory_name('it_IT')
219 u'Germania'
220 >>> l.get_territory_name('pt_PT')
221 u'Alemanha'
222
223 Calendar Display Names
224 The Locale class provides access to many locale display names related
225 to calendar display, such as the names of weekdays or months.
226
227 These display names are of course used for date formatting, but can
228 also be used, for example, to show a list of months to the user in
229 their preferred language:
230
231 >>> locale = Locale('es')
232 >>> month_names = locale.months['format']['wide'].items()
233 >>> for idx, name in sorted(month_names):
234 ... print name
235 enero
236 febrero
237 marzo
238 abril
239 mayo
240 junio
241 julio
242 agosto
243 septiembre
244 octubre
245 noviembre
246 diciembre
247
248 Date and Time
249 When working with date and time information in Python, you commonly use
250 the classes date, datetime and/or time from the datetime package. Ba‐
251 bel provides functions for locale-specific formatting of those objects
252 in its dates module:
253
254 >>> from datetime import date, datetime, time
255 >>> from babel.dates import format_date, format_datetime, format_time
256
257 >>> d = date(2007, 4, 1)
258 >>> format_date(d, locale='en')
259 u'Apr 1, 2007'
260 >>> format_date(d, locale='de_DE')
261 u'01.04.2007'
262
263 As this example demonstrates, Babel will automatically choose a date
264 format that is appropriate for the requested locale.
265
266 The format_*() functions also accept an optional format argument, which
267 allows you to choose between one of four format variations:
268
269 • short,
270
271 • medium (the default),
272
273 • long, and
274
275 • full.
276
277 For example:
278
279 >>> format_date(d, format='short', locale='en')
280 u'4/1/07'
281 >>> format_date(d, format='long', locale='en')
282 u'April 1, 2007'
283 >>> format_date(d, format='full', locale='en')
284 u'Sunday, April 1, 2007'
285
286 Core Time Concepts
287 Working with dates and time can be a complicated thing. Babel attempts
288 to simplify working with them by making some decisions for you.
289 Python’s datetime module has different ways to deal with times and
290 dates: naive and timezone-aware datetime objects.
291
292 Babel generally recommends you to store all your time in naive datetime
293 objects and treat them as UTC at all times. This simplifies dealing
294 with time a lot because otherwise you can get into the hairy situation
295 where you are dealing with datetime objects of different timezones.
296 That is tricky because there are situations where time can be ambigu‐
297 ous. This is usually the case when dealing with dates around timezone
298 transitions. The most common case of timezone transition is changes
299 between daylight saving time and standard time.
300
301 As such we recommend to always use UTC internally and only reformat to
302 local time when returning dates to users. At that point the timezone
303 the user has selected can usually be established and Babel can automat‐
304 ically rebase the time for you.
305
306 To get the current time use the utcnow() method of the datetime object.
307 It will return a naive datetime object in UTC.
308
309 For more information about timezones see Time-zone Support.
310
311 Pattern Syntax
312 While Babel makes it simple to use the appropriate date/time format for
313 a given locale, you can also force it to use custom patterns. Note that
314 Babel uses different patterns for specifying number and date formats
315 compared to the Python equivalents (such as time.strftime()), which
316 have mostly been inherited from C and POSIX. The patterns used in Babel
317 are based on the Locale Data Markup Language specification (LDML),
318 which defines them as follows:
319 A date/time pattern is a string of characters, where specific
320 strings of characters are replaced with date and time data from a
321 calendar when formatting or used to generate data for a calendar
322 when parsing. […]
323
324 Characters may be used multiple times. For example, if y is used for
325 the year, yy might produce “99”, whereas yyyy produces “1999”. For
326 most numerical fields, the number of characters specifies the field
327 width. For example, if h is the hour, h might produce “5”, but hh
328 produces “05”. For some characters, the count specifies whether an
329 abbreviated or full form should be used […]
330
331 Two single quotes represent a literal single quote, either inside or
332 outside single quotes. Text within single quotes is not interpreted
333 in any way (except for two adjacent single quotes).
334
335 For example:
336
337 >>> d = date(2007, 4, 1)
338 >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
339 u"Sun, Apr 1, '07"
340 >>> format_date(d, "EEEE, d.M.yyyy", locale='de')
341 u'Sonntag, 1.4.2007'
342
343 >>> t = time(15, 30)
344 >>> format_time(t, "hh 'o''clock' a", locale='en')
345 u"03 o'clock PM"
346 >>> format_time(t, 'H:mm a', locale='de')
347 u'15:30 nachm.'
348
349 >>> dt = datetime(2007, 4, 1, 15, 30)
350 >>> format_datetime(dt, "yyyyy.MMMM.dd GGG hh:mm a", locale='en')
351 u'02007.April.01 AD 03:30 PM'
352
353 The syntax for custom datetime format patterns is described in detail
354 in the the Locale Data Markup Language specification. The following ta‐
355 ble is just a relatively brief overview.
356
357 Date Fields
358 ┌─────────┬─────────────────────┬─────────────────────┐
359 │Field │ Symbol │ Description │
360 ├─────────┼─────────────────────┼─────────────────────┤
361 │Era │ G │ Replaced with the │
362 │ │ │ era string for the │
363 │ │ │ current date. One │
364 │ │ │ to three letters │
365 │ │ │ for the abbreviated │
366 │ │ │ form, four letters‐ │
367 │ │ │ for the long form, │
368 │ │ │ five for the narrow │
369 │ │ │ form │
370 ├─────────┼─────────────────────┼─────────────────────┤
371 │Year │ y │ Replaced by the │
372 │ │ │ year. Normally the │
373 │ │ │ length specifies │
374 │ │ │ the padding, but │
375 │ │ │ for two letters it │
376 │ │ │ also specifies the │
377 │ │ │ maximum length. │
378 ├─────────┼─────────────────────┼─────────────────────┤
379 │Y │ Same as y but uses │ │
380 │ │ the ISO year-week │ │
381 │ │ calendar. ISO │ │
382 │ │ year-week incre‐ │ │
383 │ │ ments after com‐ │ │
384 │ │ pleting the last │ │
385 │ │ week of the year. │ │
386 │ │ Therefore it may │ │
387 │ │ change a few days │ │
388 │ │ before or after y. │ │
389 │ │ Recommend use with │ │
390 │ │ the w Symbol. │ │
391 ├─────────┼─────────────────────┼─────────────────────┤
392 │u │ ?? │ │
393 └─────────┴─────────────────────┴─────────────────────┘
394
395
396
397
398
399
400
401 │Quarter │ Q │ Use one or two for │
402 │ │ │ the numerical quar‐ │
403 │ │ │ ter, three for the │
404 │ │ │ abbreviation, or │
405 │ │ │ four for the full │
406 │ │ │ name. │
407 ├─────────┼─────────────────────┼─────────────────────┤
408 │q │ Use one or two for │ │
409 │ │ the numerical quar‐ │ │
410 │ │ ter, three for the │ │
411 │ │ abbreviation, or │ │
412 │ │ four for the full │ │
413 │ │ name. │ │
414 ├─────────┼─────────────────────┼─────────────────────┤
415 │Month │ M │ Use one or two for │
416 │ │ │ the numerical │
417 │ │ │ month, three for │
418 │ │ │ the abbreviation, │
419 │ │ │ or four for the │
420 │ │ │ full name, or five │
421 │ │ │ for the narrow │
422 │ │ │ name. │
423 ├─────────┼─────────────────────┼─────────────────────┤
424 │L │ Use one or two for │ │
425 │ │ the numerical │ │
426 │ │ month, three for │ │
427 │ │ the abbreviation, │ │
428 │ │ or four for the │ │
429 │ │ full name, or 5 for │ │
430 │ │ the narrow name. │ │
431 ├─────────┼─────────────────────┼─────────────────────┤
432 │Week │ w │ Week of year ac‐ │
433 │ │ │ cording to the ISO │
434 │ │ │ year-week calendar. │
435 │ │ │ This may have 52 or │
436 │ │ │ 53 weeks depending │
437 │ │ │ on the year. Rec‐ │
438 │ │ │ ommend use with the │
439 │ │ │ Y symbol. │
440 ├─────────┼─────────────────────┼─────────────────────┤
441 │W │ Week of month. │ │
442 ├─────────┼─────────────────────┼─────────────────────┤
443 │Day │ d │ Day of month. │
444 ├─────────┼─────────────────────┼─────────────────────┤
445 │D │ Day of year. │ │
446 ├─────────┼─────────────────────┼─────────────────────┤
447 │F │ Day of week in │ │
448 │ │ month. │ │
449 ├─────────┼─────────────────────┼─────────────────────┤
450 │g │ ?? │ │
451 ├─────────┼─────────────────────┼─────────────────────┤
452 │Week day │ E │ Day of week. Use │
453 │ │ │ one through three │
454 │ │ │ letters for the │
455 │ │ │ short day, or four │
456 │ │ │ for the full name, │
457 │ │ │ or five for the │
458 │ │ │ narrow name. │
459 └─────────┴─────────────────────┴─────────────────────┘
460
461
462
463
464
465
466
467
468 │e │ Local day of week. │ │
469 │ │ Same as E except │ │
470 │ │ adds a numeric │ │
471 │ │ value that will de‐ │ │
472 │ │ pend on the local │ │
473 │ │ starting day of the │ │
474 │ │ week, using one or │ │
475 │ │ two letters. │ │
476 ├─────────┼─────────────────────┼─────────────────────┤
477 │c │ ?? │ │
478 └─────────┴─────────────────────┴─────────────────────┘
479
480 Time Fields
481 ┌─────────┬─────────────────────┬─────────────────────┐
482 │Field │ Symbol │ Description │
483 ├─────────┼─────────────────────┼─────────────────────┤
484 │Period │ a │ AM or PM │
485 ├─────────┼─────────────────────┼─────────────────────┤
486 │Hour │ h │ Hour [1-12]. │
487 ├─────────┼─────────────────────┼─────────────────────┤
488 │H │ Hour [0-23]. │ │
489 ├─────────┼─────────────────────┼─────────────────────┤
490 │K │ Hour [0-11]. │ │
491 ├─────────┼─────────────────────┼─────────────────────┤
492 │k │ Hour [1-24]. │ │
493 ├─────────┼─────────────────────┼─────────────────────┤
494 │Minute │ m │ Use one or two for │
495 │ │ │ zero places pad‐ │
496 │ │ │ ding. │
497 ├─────────┼─────────────────────┼─────────────────────┤
498 │Second │ s │ Use one or two for │
499 │ │ │ zero places pad‐ │
500 │ │ │ ding. │
501 ├─────────┼─────────────────────┼─────────────────────┤
502 │S │ Fractional second, │ │
503 │ │ rounds to the count │ │
504 │ │ of letters. │ │
505 ├─────────┼─────────────────────┼─────────────────────┤
506 │A │ Milliseconds in │ │
507 │ │ day. │ │
508 ├─────────┼─────────────────────┼─────────────────────┤
509 │Timezone │ z │ Use one to three │
510 │ │ │ letters for the │
511 │ │ │ short timezone or │
512 │ │ │ four for the full │
513 │ │ │ name. │
514 ├─────────┼─────────────────────┼─────────────────────┤
515 │Z │ Use one to three │ │
516 │ │ letters for RFC │ │
517 │ │ 822, four letters │ │
518 │ │ for GMT format. │ │
519 ├─────────┼─────────────────────┼─────────────────────┤
520 │v │ Use one letter for │ │
521 │ │ short wall │ │
522 │ │ (generic) time, │ │
523 │ │ four for long wall │ │
524 │ │ time. │ │
525 ├─────────┼─────────────────────┼─────────────────────┤
526 │V │ Same as z, except │ │
527 │ │ that timezone ab‐ │ │
528 │ │ breviations should │ │
529 │ │ be used regardless │ │
530 │ │ of whether they are │ │
531 │ │ in common use by │ │
532 │ │ the locale. │ │
533 └─────────┴─────────────────────┴─────────────────────┘
534
535 Time Delta Formatting
536 In addition to providing functions for formatting localized dates and
537 times, the babel.dates module also provides a function to format the
538 difference between two times, called a ‘’time delta’’. These are usu‐
539 ally represented as datetime.timedelta objects in Python, and it’s also
540 what you get when you subtract one datetime object from an other.
541
542 The format_timedelta function takes a timedelta object and returns a
543 human-readable representation. This happens at the cost of precision,
544 as it chooses only the most significant unit (such as year, week, or
545 hour) of the difference, and displays that:
546
547 >>> from datetime import timedelta
548 >>> from babel.dates import format_timedelta
549 >>> delta = timedelta(days=6)
550 >>> format_timedelta(delta, locale='en_US')
551 u'1 week'
552
553 The resulting strings are based from the CLDR data, and are properly
554 pluralized depending on the plural rules of the locale and the calcu‐
555 lated number of units.
556
557 The function provides parameters for you to influence how this most
558 significant unit is chosen: with threshold you set the value after
559 which the presentation switches to the next larger unit, and with gran‐
560 ularity you can limit the smallest unit to display:
561
562 >>> delta = timedelta(days=6)
563 >>> format_timedelta(delta, threshold=1.2, locale='en_US')
564 u'6 days'
565 >>> format_timedelta(delta, granularity='month', locale='en_US')
566 u'1 month'
567
568 Time-zone Support
569 Many of the verbose time formats include the time-zone, but time-zone
570 information is not by default available for the Python datetime and
571 time objects. The standard library includes only the abstract tzinfo
572 class, which you need appropriate implementations for to actually use
573 in your application. Babel includes a tzinfo implementation for UTC
574 (Universal Time).
575
576 Babel uses pytz for real timezone support which includes the defini‐
577 tions of practically all of the time-zones used on the world, as well
578 as important functions for reliably converting from UTC to local time,
579 and vice versa. The module is generally wrapped for you so you can di‐
580 rectly interface with it from within Babel:
581
582 >>> from datetime import time
583 >>> from babel.dates import get_timezone, UTC
584 >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=UTC)
585 >>> eastern = get_timezone('US/Eastern')
586 >>> format_datetime(dt, 'H:mm Z', tzinfo=eastern, locale='en_US')
587 u'11:30 -0400'
588
589 The recommended approach to deal with different time-zones in a Python
590 application is to always use UTC internally, and only convert from/to
591 the users time-zone when accepting user input and displaying date/time
592 data, respectively. You can use Babel together with pytz to apply a
593 time-zone to any datetime or time object for display, leaving the orig‐
594 inal information unchanged:
595
596 >>> british = get_timezone('Europe/London')
597 >>> format_datetime(dt, 'H:mm zzzz', tzinfo=british, locale='en_US')
598 u'16:30 British Summer Time'
599
600 Here, the given UTC time is adjusted to the “Europe/London” time-zone,
601 and daylight savings time is taken into account. Daylight savings time
602 is also applied to format_time, but because the actual date is unknown
603 in that case, the current day is assumed to determine whether DST or
604 standard time should be used.
605
606 For many timezones it’s also possible to ask for the next timezone
607 transition. This for instance is useful to answer the question “when
608 do I have to move the clock forward next”:
609
610 >>> t = get_next_timezone_transition('Europe/Vienna', datetime(2011, 3, 2))
611 >>> t
612 <TimezoneTransition CET -> CEST (2011-03-27 01:00:00)>
613 >>> t.from_offset
614 3600.0
615 >>> t.to_offset
616 7200.0
617 >>> t.from_tz
618 'CET'
619 >>> t.to_tz
620 'CEST'
621
622 Lastly Babel also provides support for working with the local timezone
623 of your operating system. It’s provided through the LOCALTZ constant:
624
625 >>> from babel.dates import LOCALTZ, get_timezone_name
626 >>> LOCALTZ
627 <DstTzInfo 'Europe/Vienna' CET+1:00:00 STD>
628 >>> get_timezone_name(LOCALTZ)
629 u'Central European Time'
630
631 Localized Time-zone Names
632 While the Locale class provides access to various locale display names
633 related to time-zones, the process of building a localized name of a
634 time-zone is actually quite complicated. Babel implements it in sepa‐
635 rately usable functions in the babel.dates module, most importantly the
636 get_timezone_name function:
637
638 >>> from babel import Locale
639 >>> from babel.dates import get_timezone_name, get_timezone
640
641 >>> tz = get_timezone('Europe/Berlin')
642 >>> get_timezone_name(tz, locale=Locale.parse('pt_PT'))
643 u'Hora da Europa Central'
644
645 You can pass the function either a datetime.tzinfo object, or a date‐
646 time.date or datetime.datetime object. If you pass an actual date, the
647 function will be able to take daylight savings time into account. If
648 you pass just the time-zone, Babel does not know whether daylight sav‐
649 ings time is in effect, so it uses a generic representation, which is
650 useful for example to display a list of time-zones to the user.
651
652 >>> from datetime import datetime
653
654 >>> dt = tz.localize(datetime(2007, 8, 15))
655 >>> get_timezone_name(dt, locale=Locale.parse('de_DE'))
656 u'Mitteleurop\xe4ische Sommerzeit'
657 >>> get_timezone_name(tz, locale=Locale.parse('de_DE'))
658 u'Mitteleurop\xe4ische Zeit'
659
660 Number Formatting
661 Support for locale-specific formatting and parsing of numbers is pro‐
662 vided by the babel.numbers module:
663
664 >>> from babel.numbers import format_number, format_decimal, format_percent
665
666 Examples:
667
668 # Numbers with decimal places
669 >>> format_decimal(1.2345, locale='en_US')
670 u'1.234'
671 >>> format_decimal(1.2345, locale='sv_SE')
672 u'1,234'
673 # Integers with thousand grouping
674 >>> format_decimal(12345, locale='de_DE')
675 u'12.345'
676 >>> format_decimal(12345678, locale='de_DE')
677 u'12.345.678'
678
679 Pattern Syntax
680 While Babel makes it simple to use the appropriate number format for a
681 given locale, you can also force it to use custom patterns. As with
682 date/time formatting patterns, the patterns Babel supports for number
683 formatting are based on the Locale Data Markup Language specification
684 (LDML).
685
686 Examples:
687
688 >>> format_decimal(-1.2345, format='#,##0.##;-#', locale='en')
689 u'-1.23'
690 >>> format_decimal(-1.2345, format='#,##0.##;(#)', locale='en')
691 u'(1.23)'
692
693 The syntax for custom number format patterns is described in detail in
694 the the specification. The following table is just a relatively brief
695 overview.
696
697 ┌───────┬────────────────────────────┐
698 │Symbol │ Description │
699 ├───────┼────────────────────────────┤
700 │0 │ Digit │
701 ├───────┼────────────────────────────┤
702 │1-9 │ ‘1’ through ‘9’ indicate │
703 │ │ rounding. │
704 ├───────┼────────────────────────────┤
705 │@ │ Significant digit │
706 ├───────┼────────────────────────────┤
707 │# │ Digit, zero shows as ab‐ │
708 │ │ sent │
709 ├───────┼────────────────────────────┤
710 │. │ Decimal separator or mone‐ │
711 │ │ tary decimal separator │
712 ├───────┼────────────────────────────┤
713 │- │ Minus sign │
714 ├───────┼────────────────────────────┤
715 │, │ Grouping separator │
716 ├───────┼────────────────────────────┤
717 │E │ Separates mantissa and ex‐ │
718 │ │ ponent in scientific nota‐ │
719 │ │ tion │
720 ├───────┼────────────────────────────┤
721 │+ │ Prefix positive exponents │
722 │ │ with localized plus sign │
723 ├───────┼────────────────────────────┤
724 │; │ Separates positive and │
725 │ │ negative subpatterns │
726 ├───────┼────────────────────────────┤
727 │% │ Multiply by 100 and show │
728 │ │ as percentage │
729 ├───────┼────────────────────────────┤
730 │‰ │ Multiply by 1000 and show │
731 │ │ as per mille │
732 └───────┴────────────────────────────┘
733
734
735
736 │¤ │ Currency sign, replaced by │
737 │ │ currency symbol. If dou‐ │
738 │ │ bled, replaced by interna‐ │
739 │ │ tional currency symbol. If │
740 │ │ tripled, uses the long │
741 │ │ form of the decimal sym‐ │
742 │ │ bol. │
743 ├───────┼────────────────────────────┤
744 │' │ Used to quote special │
745 │ │ characters in a prefix or │
746 │ │ suffix │
747 ├───────┼────────────────────────────┤
748 │* │ Pad escape, precedes pad │
749 │ │ character │
750 └───────┴────────────────────────────┘
751
752 Rounding Modes
753 Since Babel makes full use of Python’s Decimal type to perform number
754 rounding before formatting, users have the chance to control the round‐
755 ing mode and other configurable parameters through the active Context
756 instance.
757
758 By default, Python rounding mode is ROUND_HALF_EVEN which complies with
759 UTS #35 section 3.3. Yet, the caller has the opportunity to tweak the
760 current context before formatting a number or currency:
761
762 >>> from babel.numbers import decimal, format_decimal
763 >>> with decimal.localcontext(decimal.Context(rounding=decimal.ROUND_DOWN)):
764 >>> txt = format_decimal(123.99, format='#', locale='en_US')
765 >>> txt
766 u'123'
767
768 It is also possible to use decimal.setcontext or directly modifying the
769 instance returned by decimal.getcontext. However, using a context man‐
770 ager is always more convenient due to the automatic restoration and the
771 ability to nest them.
772
773 Whatever mechanism is chosen, always make use of the decimal module im‐
774 ported from babel.numbers. For efficiency reasons, Babel uses the
775 fastest decimal implementation available, such as cdecimal. These var‐
776 ious implementation offer an identical API, but their types and in‐
777 stances do not interoperate with each other.
778
779 For example, the previous example can be slightly modified to generate
780 unexpected results on Python 2.7, with the cdecimal module installed:
781
782 >>> from decimal import localcontext, Context, ROUND_DOWN
783 >>> from babel.numbers import format_decimal
784 >>> with localcontext(Context(rounding=ROUND_DOWN)):
785 >>> txt = format_decimal(123.99, format='#', locale='en_US')
786 >>> txt
787 u'124'
788
789 Changing other parameters such as the precision may also alter the re‐
790 sults of the number formatting functions. Remember to test your code
791 to make sure it behaves as desired.
792
793 Parsing Numbers
794 Babel can also parse numeric data in a locale-sensitive manner:
795
796 >>> from babel.numbers import parse_decimal, parse_number
797
798 Examples:
799
800 >>> parse_decimal('1,099.98', locale='en_US')
801 1099.98
802 >>> parse_decimal('1.099,98', locale='de')
803 1099.98
804 >>> parse_decimal('2,109,998', locale='de')
805 Traceback (most recent call last):
806 ...
807 NumberFormatError: '2,109,998' is not a valid decimal number
808
809 Note: as of version 2.8.0, the parse_number function has limited func‐
810 tionality. It can remove group symbols of certain locales from numeric
811 strings, but may behave unexpectedly until its logic handles more en‐
812 coding issues and other special cases.
813
814 Examples:
815
816 >>> parse_number('1,099', locale='en_US')
817 1099
818 >>> parse_number('1.099.024', locale='de')
819 1099024
820 >>> parse_number('123' + u'\xa0' + '4567', locale='ru')
821 1234567
822 >>> parse_number('123 4567', locale='ru')
823 ...
824 NumberFormatError: '123 4567' is not a valid number
825
826 Working with Message Catalogs
827 Introduction
828 The gettext translation system enables you to mark any strings used in
829 your application as subject to localization, by wrapping them in func‐
830 tions such as gettext(str) and ngettext(singular, plural, num). For
831 brevity, the gettext function is often aliased to _(str), so you can
832 write:
833
834 print(_("Hello"))
835
836 instead of just:
837
838 print("Hello")
839
840 to make the string “Hello” localizable.
841
842 Message catalogs are collections of translations for such localizable
843 messages used in an application. They are commonly stored in PO (Porta‐
844 ble Object) and MO (Machine Object) files, the formats of which are de‐
845 fined by the GNU gettext tools and the GNU translation project.
846
847 The general procedure for building message catalogs looks something
848 like this:
849
850 • use a tool (such as xgettext) to extract localizable strings from
851 the code base and write them to a POT (PO Template) file.
852
853 • make a copy of the POT file for a specific locale (for example,
854 “en_US”) and start translating the messages
855
856 • use a tool such as msgfmt to compile the locale PO file into a bi‐
857 nary MO file
858
859 • later, when code changes make it necessary to update the transla‐
860 tions, you regenerate the POT file and merge the changes into the
861 various locale-specific PO files, for example using msgmerge
862
863 Python provides the gettext module as part of the standard library,
864 which enables applications to work with appropriately generated MO
865 files.
866
867 As gettext provides a solid and well supported foundation for translat‐
868 ing application messages, Babel does not reinvent the wheel, but rather
869 reuses this infrastructure, and makes it easier to build message cata‐
870 logs for Python applications.
871
872 Message Extraction
873 Babel provides functionality similar to that of the xgettext program,
874 except that only extraction from Python source files is built-in, while
875 support for other file formats can be added using a simple extension
876 mechanism.
877
878 Unlike xgettext, which is usually invoked once for every file, the rou‐
879 tines for message extraction in Babel operate on directories. While the
880 per-file approach of xgettext works nicely with projects using a Make‐
881 file, Python projects rarely use make, and thus a different mechanism
882 is needed for extracting messages from the heterogeneous collection of
883 source files that many Python projects are composed of.
884
885 When message extraction is based on directories instead of individual
886 files, there needs to be a way to configure which files should be
887 treated in which manner. For example, while many projects may contain
888 .html files, some of those files may be static HTML files that don’t
889 contain localizable message, while others may be Jinja2 templates, and
890 still others may contain Genshi markup templates. Some projects may
891 even mix HTML files for different templates languages (for whatever
892 reason). Therefore the way in which messages are extracted from source
893 files can not only depend on the file extension, but needs to be con‐
894 trollable in a precise manner.
895
896 Babel accepts a configuration file to specify this mapping of files to
897 extraction methods, which is described below.
898
899 Front-Ends
900 Babel provides two different front-ends to access its functionality for
901 working with message catalogs:
902
903 • A Command-Line Interface, and
904
905 • Distutils/Setuptools Integration
906
907 Which one you choose depends on the nature of your project. For most
908 modern Python projects, the distutils/setuptools integration is proba‐
909 bly more convenient.
910
911 Extraction Method Mapping and Configuration
912 The mapping of extraction methods to files in Babel is done via a con‐
913 figuration file. This file maps extended glob patterns to the names of
914 the extraction methods, and can also set various options for each pat‐
915 tern (which options are available depends on the specific extraction
916 method).
917
918 For example, the following configuration adds extraction of messages
919 from both Genshi markup templates and text templates:
920
921 # Extraction from Python source files
922
923 [python: **.py]
924
925 # Extraction from Genshi HTML and text templates
926
927 [genshi: **/templates/**.html]
928 ignore_tags = script,style
929 include_attrs = alt title summary
930
931 [genshi: **/templates/**.txt]
932 template_class = genshi.template:TextTemplate
933 encoding = ISO-8819-15
934
935 # Extraction from JavaScript files
936
937 [javascript: **.js]
938 extract_messages = $._, jQuery._
939
940 The configuration file syntax is based on the format commonly found in
941 .INI files on Windows systems, and as supported by the ConfigParser
942 module in the Python standard library. Section names (the strings en‐
943 closed in square brackets) specify both the name of the extraction
944 method, and the extended glob pattern to specify the files that this
945 extraction method should be used for, separated by a colon. The options
946 in the sections are passed to the extraction method. Which options are
947 available is specific to the extraction method used.
948
949 The extended glob patterns used in this configuration are similar to
950 the glob patterns provided by most shells. A single asterisk (*) is a
951 wildcard for any number of characters (except for the pathname compo‐
952 nent separator “/”), while a question mark (?) only matches a single
953 character. In addition, two subsequent asterisk characters (**) can be
954 used to make the wildcard match any directory level, so the pattern
955 **.txt matches any file with the extension .txt in any directory.
956
957 Lines that start with a # or ; character are ignored and can be used
958 for comments. Empty lines are ignored, too.
959
960 NOTE:
961 if you’re performing message extraction using the command Babel pro‐
962 vides for integration into setup.py scripts, you can also provide
963 this configuration in a different way, namely as a keyword argument
964 to the setup() function. See Distutils/Setuptools Integration for
965 more information.
966
967 Default Extraction Methods
968 Babel comes with a few builtin extractors: python (which extracts mes‐
969 sages from Python source files), javascript, and ignore (which extracts
970 nothing).
971
972 The python extractor is by default mapped to the glob pattern **.py,
973 meaning it’ll be applied to all files with the .py extension in any di‐
974 rectory. If you specify your own mapping configuration, this default
975 mapping is discarded, so you need to explicitly add it to your mapping
976 (as shown in the example above.)
977
978 Referencing Extraction Methods
979 To be able to use short extraction method names such as “genshi”, you
980 need to have pkg_resources installed, and the package implementing that
981 extraction method needs to have been installed with its meta data (the
982 egg-info).
983
984 If this is not possible for some reason, you need to map the short
985 names to fully qualified function names in an extract section in the
986 mapping configuration. For example:
987
988 # Some custom extraction method
989
990 [extractors]
991 custom = mypackage.module:extract_custom
992
993 [custom: **.ctm]
994 some_option = foo
995
996 Note that the builtin extraction methods python and ignore are avail‐
997 able by default, even if pkg_resources is not installed. You should
998 never need to explicitly define them in the [extractors] section.
999
1000 Writing Extraction Methods
1001 Adding new methods for extracting localizable methods is easy. First,
1002 you’ll need to implement a function that complies with the following
1003 interface:
1004
1005 def extract_xxx(fileobj, keywords, comment_tags, options):
1006 """Extract messages from XXX files.
1007
1008 :param fileobj: the file-like object the messages should be extracted
1009 from
1010 :param keywords: a list of keywords (i.e. function names) that should
1011 be recognized as translation functions
1012 :param comment_tags: a list of translator tags to search for and
1013 include in the results
1014 :param options: a dictionary of additional options (optional)
1015 :return: an iterator over ``(lineno, funcname, message, comments)``
1016 tuples
1017 :rtype: ``iterator``
1018 """
1019
1020 NOTE:
1021 Any strings in the tuples produced by this function must be either
1022 unicode objects, or str objects using plain ASCII characters. That
1023 means that if sources contain strings using other encodings, it is
1024 the job of the extractor implementation to do the decoding to uni‐
1025 code objects.
1026
1027 Next, you should register that function as an entry point. This re‐
1028 quires your setup.py script to use setuptools, and your package to be
1029 installed with the necessary metadata. If that’s taken care of, add
1030 something like the following to your setup.py script:
1031
1032 def setup(...
1033
1034 entry_points = """
1035 [babel.extractors]
1036 xxx = your.package:extract_xxx
1037 """,
1038
1039 That is, add your extraction method to the entry point group babel.ex‐
1040 tractors, where the name of the entry point is the name that people
1041 will use to reference the extraction method, and the value being the
1042 module and the name of the function (separated by a colon) implementing
1043 the actual extraction.
1044
1045 NOTE:
1046 As shown in Referencing Extraction Methods, declaring an entry point
1047 is not strictly required, as users can still reference the extrac‐
1048 tion function directly. But whenever possible, the entry point
1049 should be declared to make configuration more convenient.
1050
1051 Translator Comments
1052 First of all what are comments tags. Comments tags are excerpts of text
1053 to search for in comments, only comments, right before the python get‐
1054 text calls, as shown on the following example:
1055
1056 # NOTE: This is a comment about `Foo Bar`
1057 _('Foo Bar')
1058
1059 The comments tag for the above example would be NOTE:, and the transla‐
1060 tor comment for that tag would be This is a comment about `Foo Bar`.
1061
1062 The resulting output in the catalog template would be something like:
1063
1064 #. This is a comment about `Foo Bar`
1065 #: main.py:2
1066 msgid "Foo Bar"
1067 msgstr ""
1068
1069 Now, you might ask, why would I need that?
1070
1071 Consider this simple case; you have a menu item called “manual”. You
1072 know what it means, but when the translator sees this they will wonder
1073 did you mean:
1074
1075 1. a document or help manual, or
1076
1077 2. a manual process?
1078
1079 This is the simplest case where a translation comment such as “The in‐
1080 stallation manual” helps to clarify the situation and makes a transla‐
1081 tor more productive.
1082
1083 NOTE:
1084 Whether translator comments can be extracted depends on the extrac‐
1085 tion method in use. The Python extractor provided by Babel does im‐
1086 plement this feature, but others may not.
1087
1088 Command-Line Interface
1089 Babel includes a command-line interface for working with message cata‐
1090 logs, similar to the various GNU gettext tools commonly available on
1091 Linux/Unix systems.
1092
1093 When properly installed, Babel provides a script called pybabel:
1094
1095 $ pybabel --help
1096 Usage: pybabel command [options] [args]
1097
1098 Options:
1099 --version show program's version number and exit
1100 -h, --help show this help message and exit
1101 --list-locales print all known locales and exit
1102 -v, --verbose print as much as possible
1103 -q, --quiet print as little as possible
1104
1105 commands:
1106 compile compile message catalogs to MO files
1107 extract extract messages from source files and generate a POT file
1108 init create new message catalogs from a POT file
1109 update update existing message catalogs from a POT file
1110
1111 The pybabel script provides a number of sub-commands that do the actual
1112 work. Those sub-commands are described below.
1113
1114 compile
1115 The compile sub-command can be used to compile translation catalogs
1116 into binary MO files:
1117
1118 $ pybabel compile --help
1119 Usage: pybabel compile [options]
1120
1121 compile message catalogs to MO files
1122
1123 Options:
1124 -h, --help show this help message and exit
1125 -D DOMAIN, --domain=DOMAIN
1126 domains of PO files (space separated list, default
1127 'messages')
1128 -d DIRECTORY, --directory=DIRECTORY
1129 path to base directory containing the catalogs
1130 -i INPUT_FILE, --input-file=INPUT_FILE
1131 name of the input file
1132 -o OUTPUT_FILE, --output-file=OUTPUT_FILE
1133 name of the output file (default
1134 '<output_dir>/<locale>/LC_MESSAGES/<domain>.mo')
1135 -l LOCALE, --locale=LOCALE
1136 locale of the catalog to compile
1137 -f, --use-fuzzy also include fuzzy translations
1138 --statistics print statistics about translations
1139
1140 If directory is specified, but output-file is not, the default filename
1141 of the output file will be:
1142
1143 <directory>/<locale>/LC_MESSAGES/<domain>.mo
1144
1145 If neither the input_file nor the locale option is set, this command
1146 looks for all catalog files in the base directory that match the given
1147 domain, and compiles each of them to MO files in the same directory.
1148
1149 extract
1150 The extract sub-command can be used to extract localizable messages
1151 from a collection of source files:
1152
1153 $ pybabel extract --help
1154 Usage: pybabel extract [options] <input-paths>
1155
1156 extract messages from source files and generate a POT file
1157
1158 Options:
1159 -h, --help show this help message and exit
1160 --charset=CHARSET charset to use in the output file (default "utf-8")
1161 -k KEYWORDS, --keywords=KEYWORDS, --keyword=KEYWORDS
1162 space-separated list of keywords to look for in
1163 addition to the defaults (may be repeated multiple
1164 times)
1165 --no-default-keywords
1166 do not include the default keywords
1167 -F MAPPING_FILE, --mapping-file=MAPPING_FILE, --mapping=MAPPING_FILE
1168 path to the mapping configuration file
1169 --no-location do not include location comments with filename and
1170 line number
1171 --add-location=ADD_LOCATION
1172 location lines format. If it is not given or "full",
1173 it generates the lines with both file name and line
1174 number. If it is "file", the line number part is
1175 omitted. If it is "never", it completely suppresses
1176 the lines (same as --no-location).
1177 --omit-header do not include msgid "" entry in header
1178 -o OUTPUT_FILE, --output-file=OUTPUT_FILE, --output=OUTPUT_FILE
1179 name of the output file
1180 -w WIDTH, --width=WIDTH
1181 set output line width (default 76)
1182 --no-wrap do not break long message lines, longer than the
1183 output line width, into several lines
1184 --sort-output generate sorted output (default False)
1185 --sort-by-file sort output by file location (default False)
1186 --msgid-bugs-address=MSGID_BUGS_ADDRESS
1187 set report address for msgid
1188 --copyright-holder=COPYRIGHT_HOLDER
1189 set copyright holder in output
1190 --project=PROJECT set project name in output
1191 --version=VERSION set project version in output
1192 -c ADD_COMMENTS, --add-comments=ADD_COMMENTS
1193 place comment block with TAG (or those preceding
1194 keyword lines) in output file. Separate multiple TAGs
1195 with commas(,)
1196 -s, --strip-comments, --strip-comment-tags
1197 strip the comment TAGs from the comments.
1198 --input-dirs=INPUT_DIRS
1199 alias for input-paths (does allow files as well as
1200 directories).
1201
1202 init
1203 The init sub-command creates a new translations catalog based on a PO
1204 template file:
1205
1206 $ pybabel init --help
1207 Usage: pybabel init [options]
1208
1209 create new message catalogs from a POT file
1210
1211 Options:
1212 -h, --help show this help message and exit
1213 -D DOMAIN, --domain=DOMAIN
1214 domain of PO file (default 'messages')
1215 -i INPUT_FILE, --input-file=INPUT_FILE
1216 name of the input file
1217 -d OUTPUT_DIR, --output-dir=OUTPUT_DIR
1218 path to output directory
1219 -o OUTPUT_FILE, --output-file=OUTPUT_FILE
1220 name of the output file (default
1221 '<output_dir>/<locale>/LC_MESSAGES/<domain>.po')
1222 -l LOCALE, --locale=LOCALE
1223 locale for the new localized catalog
1224 -w WIDTH, --width=WIDTH
1225 set output line width (default 76)
1226 --no-wrap do not break long message lines, longer than the
1227 output line width, into several lines
1228
1229 update
1230 The update sub-command updates an existing new translations catalog
1231 based on a PO template file:
1232
1233 $ pybabel update --help
1234 Usage: pybabel update [options]
1235
1236 update existing message catalogs from a POT file
1237
1238 Options:
1239 -h, --help show this help message and exit
1240 -D DOMAIN, --domain=DOMAIN
1241 domain of PO file (default 'messages')
1242 -i INPUT_FILE, --input-file=INPUT_FILE
1243 name of the input file
1244 -d OUTPUT_DIR, --output-dir=OUTPUT_DIR
1245 path to base directory containing the catalogs
1246 -o OUTPUT_FILE, --output-file=OUTPUT_FILE
1247 name of the output file (default
1248 '<output_dir>/<locale>/LC_MESSAGES/<domain>.po')
1249 --omit-header do not include msgid entry in header
1250 -l LOCALE, --locale=LOCALE
1251 locale of the catalog to compile
1252 -w WIDTH, --width=WIDTH
1253 set output line width (default 76)
1254 --no-wrap do not break long message lines, longer than the
1255 output line width, into several lines
1256 --ignore-obsolete whether to omit obsolete messages from the output
1257 --init-missing if any output files are missing, initialize them first
1258 -N, --no-fuzzy-matching
1259 do not use fuzzy matching
1260 --update-header-comment
1261 update target header comment
1262 --previous keep previous msgids of translated messages
1263
1264 If output_dir is specified, but output-file is not, the default file‐
1265 name of the output file will be:
1266
1267 <directory>/<locale>/LC_MESSAGES/<domain>.mo
1268
1269 If neither the output_file nor the locale option is set, this command
1270 looks for all catalog files in the base directory that match the given
1271 domain, and updates each of them.
1272
1273 Distutils/Setuptools Integration
1274 Babel provides commands for integration into setup.py scripts, based on
1275 either the distutils package that is part of the Python standard li‐
1276 brary, or the third-party setuptools package.
1277
1278 These commands are available by default when Babel has been properly
1279 installed, and setup.py is using setuptools. For projects that use
1280 plain old distutils, the commands need to be registered explicitly, for
1281 example:
1282
1283 from distutils.core import setup
1284 from babel.messages import frontend as babel
1285
1286 setup(
1287 ...
1288 cmdclass = {'compile_catalog': babel.compile_catalog,
1289 'extract_messages': babel.extract_messages,
1290 'init_catalog': babel.init_catalog,
1291 'update_catalog': babel.update_catalog}
1292 )
1293
1294 compile_catalog
1295 The compile_catalog command is similar to the GNU msgfmt tool, in that
1296 it takes a message catalog from a PO file and compiles it to a binary
1297 MO file.
1298
1299 If the command has been correctly installed or registered, a project’s
1300 setup.py script should allow you to use the command:
1301
1302 $ ./setup.py compile_catalog --help
1303 Global options:
1304 --verbose (-v) run verbosely (default)
1305 --quiet (-q) run quietly (turns verbosity off)
1306 --dry-run (-n) don't actually do anything
1307 --help (-h) show detailed help message
1308
1309 Options for 'compile_catalog' command:
1310 ...
1311
1312 Running the command will produce a binary MO file:
1313
1314 $ ./setup.py compile_catalog --directory foobar/locale --locale pt_BR
1315 running compile_catalog
1316 compiling catalog to foobar/locale/pt_BR/LC_MESSAGES/messages.mo
1317
1318 Options
1319 The compile_catalog command accepts the following options:
1320
1321 ┌───────────────────┬────────────────────────────┐
1322 │Option │ Description │
1323 ├───────────────────┼────────────────────────────┤
1324 │--domain │ domain of the PO file (de‐ │
1325 │ │ faults to lower-cased │
1326 │ │ project name) │
1327 ├───────────────────┼────────────────────────────┤
1328 │--directory (-d) │ name of the base directory │
1329 ├───────────────────┼────────────────────────────┤
1330 │--input-file (-i) │ name of the input file │
1331 ├───────────────────┼────────────────────────────┤
1332 │--output-file (-o) │ name of the output file │
1333 ├───────────────────┼────────────────────────────┤
1334 │--locale (-l) │ locale for the new local‐ │
1335 │ │ ized string │
1336 └───────────────────┴────────────────────────────┘
1337
1338
1339 │--use-fuzzy (-f) │ also include “fuzzy” │
1340 │ │ translations │
1341 ├───────────────────┼────────────────────────────┤
1342 │--statistics │ print statistics about │
1343 │ │ translations │
1344 └───────────────────┴────────────────────────────┘
1345
1346 If directory is specified, but output-file is not, the default filename
1347 of the output file will be:
1348
1349 <directory>/<locale>/LC_MESSAGES/<domain>.mo
1350
1351 If neither the input_file nor the locale option is set, this command
1352 looks for all catalog files in the base directory that match the given
1353 domain, and compiles each of them to MO files in the same directory.
1354
1355 These options can either be specified on the command-line, or in the
1356 setup.cfg file.
1357
1358 extract_messages
1359 The extract_messages command is comparable to the GNU xgettext program:
1360 it can extract localizable messages from a variety of difference source
1361 files, and generate a PO (portable object) template file from the col‐
1362 lected messages.
1363
1364 If the command has been correctly installed or registered, a project’s
1365 setup.py script should allow you to use the command:
1366
1367 $ ./setup.py extract_messages --help
1368 Global options:
1369 --verbose (-v) run verbosely (default)
1370 --quiet (-q) run quietly (turns verbosity off)
1371 --dry-run (-n) don't actually do anything
1372 --help (-h) show detailed help message
1373
1374 Options for 'extract_messages' command:
1375 ...
1376
1377 Running the command will produce a PO template file:
1378
1379 $ ./setup.py extract_messages --output-file foobar/locale/messages.pot
1380 running extract_messages
1381 extracting messages from foobar/__init__.py
1382 extracting messages from foobar/core.py
1383 ...
1384 writing PO template file to foobar/locale/messages.pot
1385
1386 Method Mapping
1387 The mapping of file patterns to extraction methods (and options) can be
1388 specified using a configuration file that is pointed to using the
1389 --mapping-file option shown above. Alternatively, you can configure the
1390 mapping directly in setup.py using a keyword argument to the setup()
1391 function:
1392
1393 setup(...
1394
1395 message_extractors = {
1396 'foobar': [
1397 ('**.py', 'python', None),
1398 ('**/templates/**.html', 'genshi', None),
1399 ('**/templates/**.txt', 'genshi', {
1400 'template_class': 'genshi.template:TextTemplate'
1401 })
1402 ],
1403 },
1404
1405 ...
1406 )
1407
1408 Options
1409 The extract_messages command accepts the following options:
1410
1411 ┌──────────────────────┬────────────────────────────┐
1412 │Option │ Description │
1413 ├──────────────────────┼────────────────────────────┤
1414 │--charset │ charset to use in the out‐ │
1415 │ │ put file │
1416 ├──────────────────────┼────────────────────────────┤
1417 │--keywords (-k) │ space-separated list of │
1418 │ │ keywords to look for in │
1419 │ │ addition to the defaults │
1420 ├──────────────────────┼────────────────────────────┤
1421 │--no-default-keywords │ do not include the default │
1422 │ │ keywords │
1423 ├──────────────────────┼────────────────────────────┤
1424 │--mapping-file (-F) │ path to the mapping con‐ │
1425 │ │ figuration file │
1426 ├──────────────────────┼────────────────────────────┤
1427 │--no-location │ do not include location │
1428 │ │ comments with filename and │
1429 │ │ line number │
1430 ├──────────────────────┼────────────────────────────┤
1431 │--omit-header │ do not include msgid “” │
1432 │ │ entry in header │
1433 ├──────────────────────┼────────────────────────────┤
1434 │--output-file (-o) │ name of the output file │
1435 ├──────────────────────┼────────────────────────────┤
1436 │--width (-w) │ set output line width (de‐ │
1437 │ │ fault 76) │
1438 ├──────────────────────┼────────────────────────────┤
1439 │--no-wrap │ do not break long message │
1440 │ │ lines, longer than the │
1441 │ │ output line width, into │
1442 │ │ several lines │
1443 ├──────────────────────┼────────────────────────────┤
1444 │--input-dirs │ directories that should be │
1445 │ │ scanned for messages │
1446 ├──────────────────────┼────────────────────────────┤
1447 │--sort-output │ generate sorted output │
1448 │ │ (default False) │
1449 ├──────────────────────┼────────────────────────────┤
1450 │--sort-by-file │ sort output by file loca‐ │
1451 │ │ tion (default False) │
1452 ├──────────────────────┼────────────────────────────┤
1453 │--msgid-bugs-address │ set email address for mes‐ │
1454 │ │ sage bug reports │
1455 ├──────────────────────┼────────────────────────────┤
1456 │--copyright-holder │ set copyright holder in │
1457 │ │ output │
1458 ├──────────────────────┼────────────────────────────┤
1459 │--add-comments (-c) │ place comment block with │
1460 │ │ TAG (or those preceding │
1461 │ │ keyword lines) in output │
1462 │ │ file. Separate multiple │
1463 │ │ TAGs with commas(,) │
1464 └──────────────────────┴────────────────────────────┘
1465
1466 These options can either be specified on the command-line, or in the
1467 setup.cfg file. In the latter case, the options above become entries of
1468 the section [extract_messages], and the option names are changed to use
1469 underscore characters instead of dashes, for example:
1470
1471 [extract_messages]
1472 keywords = _ gettext ngettext
1473 mapping_file = mapping.cfg
1474 width = 80
1475
1476 This would be equivalent to invoking the command from the command-line
1477 as follows:
1478
1479 $ setup.py extract_messages -k _ -k gettext -k ngettext -F mapping.cfg -w 80
1480
1481 Any path names are interpreted relative to the location of the setup.py
1482 file. For boolean options, use “true” or “false” values.
1483
1484 init_catalog
1485 The init_catalog command is basically equivalent to the GNU msginit
1486 program: it creates a new translation catalog based on a PO template
1487 file (POT).
1488
1489 If the command has been correctly installed or registered, a project’s
1490 setup.py script should allow you to use the command:
1491
1492 $ ./setup.py init_catalog --help
1493 Global options:
1494 --verbose (-v) run verbosely (default)
1495 --quiet (-q) run quietly (turns verbosity off)
1496 --dry-run (-n) don't actually do anything
1497 --help (-h) show detailed help message
1498
1499 Options for 'init_catalog' command:
1500 ...
1501
1502 Running the command will produce a PO file:
1503
1504 $ ./setup.py init_catalog -l fr -i foobar/locales/messages.pot \
1505 -o foobar/locales/fr/messages.po
1506 running init_catalog
1507 creating catalog 'foobar/locales/fr/messages.po' based on 'foobar/locales/messages.pot'
1508
1509 Options
1510 The init_catalog command accepts the following options:
1511
1512 ┌───────────────────┬────────────────────────────┐
1513 │Option │ Description │
1514 ├───────────────────┼────────────────────────────┤
1515 │--domain │ domain of the PO file (de‐ │
1516 │ │ faults to lower-cased │
1517 │ │ project name) │
1518 ├───────────────────┼────────────────────────────┤
1519 │--input-file (-i) │ name of the input file │
1520 ├───────────────────┼────────────────────────────┤
1521 │--output-dir (-d) │ name of the output direc‐ │
1522 │ │ tory │
1523 ├───────────────────┼────────────────────────────┤
1524 │--output-file (-o) │ name of the output file │
1525 ├───────────────────┼────────────────────────────┤
1526 │--locale │ locale for the new local‐ │
1527 │ │ ized string │
1528 └───────────────────┴────────────────────────────┘
1529
1530 If output-dir is specified, but output-file is not, the default file‐
1531 name of the output file will be:
1532
1533 <output_dir>/<locale>/LC_MESSAGES/<domain>.po
1534
1535 These options can either be specified on the command-line, or in the
1536 setup.cfg file.
1537
1538 update_catalog
1539 The update_catalog command is basically equivalent to the GNU msgmerge
1540 program: it updates an existing translations catalog based on a PO tem‐
1541 plate file (POT).
1542
1543 If the command has been correctly installed or registered, a project’s
1544 setup.py script should allow you to use the command:
1545
1546 $ ./setup.py update_catalog --help
1547 Global options:
1548 --verbose (-v) run verbosely (default)
1549 --quiet (-q) run quietly (turns verbosity off)
1550 --dry-run (-n) don't actually do anything
1551 --help (-h) show detailed help message
1552
1553 Options for 'update_catalog' command:
1554 ...
1555
1556 Running the command will update a PO file:
1557
1558 $ ./setup.py update_catalog -l fr -i foobar/locales/messages.pot \
1559 -o foobar/locales/fr/messages.po
1560 running update_catalog
1561 updating catalog 'foobar/locales/fr/messages.po' based on 'foobar/locales/messages.pot'
1562
1563 Options
1564 The update_catalog command accepts the following options:
1565
1566 ┌─────────────────────────┬────────────────────────────┐
1567 │Option │ Description │
1568 ├─────────────────────────┼────────────────────────────┤
1569 │--domain │ domain of the PO file (de‐ │
1570 │ │ faults to lower-cased │
1571 │ │ project name) │
1572 ├─────────────────────────┼────────────────────────────┤
1573 │--input-file (-i) │ name of the input file │
1574 ├─────────────────────────┼────────────────────────────┤
1575 │--output-dir (-d) │ name of the output direc‐ │
1576 │ │ tory │
1577 ├─────────────────────────┼────────────────────────────┤
1578 │--output-file (-o) │ name of the output file │
1579 ├─────────────────────────┼────────────────────────────┤
1580 │--locale │ locale for the new local‐ │
1581 │ │ ized string │
1582 ├─────────────────────────┼────────────────────────────┤
1583 │--ignore-obsolete │ do not include obsolete │
1584 │ │ messages in the output │
1585 ├─────────────────────────┼────────────────────────────┤
1586 │--no-fuzzy-matching (-N) │ do not use fuzzy matching │
1587 ├─────────────────────────┼────────────────────────────┤
1588 │--previous │ keep previous msgids of │
1589 │ │ translated messages │
1590 └─────────────────────────┴────────────────────────────┘
1591
1592 If output-dir is specified, but output-file is not, the default file‐
1593 name of the output file will be:
1594
1595 <output_dir>/<locale>/LC_MESSAGES/<domain>.po
1596
1597 If neither the input_file nor the locale option is set, this command
1598 looks for all catalog files in the base directory that match the given
1599 domain, and updates each of them.
1600
1601 These options can either be specified on the command-line, or in the
1602 setup.cfg file.
1603
1604 Support Classes and Functions
1605 The babel.support modules contains a number of classes and functions
1606 that can help with integrating Babel, and internationalization in gen‐
1607 eral, into your application or framework. The code in this module is
1608 not used by Babel itself, but instead is provided to address common re‐
1609 quirements of applications that should handle internationalization.
1610
1611 Lazy Evaluation
1612 One such requirement is lazy evaluation of translations. Many web-based
1613 applications define some localizable message at the module level, or in
1614 general at some level where the locale of the remote user is not yet
1615 known. For such cases, web frameworks generally provide a “lazy” vari‐
1616 ant of the gettext functions, which basically translates the message
1617 not when the gettext function is invoked, but when the string is ac‐
1618 cessed in some manner.
1619
1620 Extended Translations Class
1621 Many web-based applications are composed of a variety of different com‐
1622 ponents (possibly using some kind of plugin system), and some of those
1623 components may provide their own message catalogs that need to be inte‐
1624 grated into the larger system.
1625
1626 To support this usage pattern, Babel provides a Translations class that
1627 is derived from the GNUTranslations class in the gettext module. This
1628 class adds a merge() method that takes another Translations instance,
1629 and merges the content of the latter into the main catalog:
1630
1631 translations = Translations.load('main')
1632 translations.merge(Translations.load('plugin1'))
1633
1635 The API reference lists the full public API that Babel provides.
1636
1637 API Reference
1638 This part of the documentation contains the full API reference of the
1639 public API of Babel.
1640
1641 Core Functionality
1642 The core API provides the basic core functionality. Primarily it pro‐
1643 vides the Locale object and ways to create it. This object encapsu‐
1644 lates a locale and exposes all the data it contains.
1645
1646 All the core functionality is also directly importable from the babel
1647 module for convenience.
1648
1649 Basic Interface
1650 class babel.core.Locale(language, territory=None, script=None, vari‐
1651 ant=None)
1652 Representation of a specific locale.
1653
1654 >>> locale = Locale('en', 'US')
1655 >>> repr(locale)
1656 "Locale('en', territory='US')"
1657 >>> locale.display_name
1658 u'English (United States)'
1659
1660 A Locale object can also be instantiated from a raw locale
1661 string:
1662
1663 >>> locale = Locale.parse('en-US', sep='-')
1664 >>> repr(locale)
1665 "Locale('en', territory='US')"
1666
1667 Locale objects provide access to a collection of locale data,
1668 such as territory and language names, number and date format
1669 patterns, and more:
1670
1671 >>> locale.number_symbols['decimal']
1672 u'.'
1673
1674 If a locale is requested for which no locale data is available,
1675 an UnknownLocaleError is raised:
1676
1677 >>> Locale.parse('en_XX')
1678 Traceback (most recent call last):
1679 ...
1680 UnknownLocaleError: unknown locale 'en_XX'
1681
1682 For more information see RFC 3066.
1683
1684 property character_order
1685 The text direction for the language.
1686
1687 >>> Locale('de', 'DE').character_order
1688 'left-to-right'
1689 >>> Locale('ar', 'SA').character_order
1690 'right-to-left'
1691
1692 property currencies
1693 Mapping of currency codes to translated currency names.
1694 This only returns the generic form of the currency name,
1695 not the count specific one. If an actual number is re‐
1696 quested use the babel.numbers.get_currency_name() func‐
1697 tion.
1698
1699 >>> Locale('en').currencies['COP']
1700 u'Colombian Peso'
1701 >>> Locale('de', 'DE').currencies['COP']
1702 u'Kolumbianischer Peso'
1703
1704 property currency_formats
1705 Locale patterns for currency number formatting.
1706
1707 NOTE:
1708 The format of the value returned may change between
1709 Babel versions.
1710
1711 >>> Locale('en', 'US').currency_formats['standard']
1712 <NumberPattern u'\xa4#,##0.00'>
1713 >>> Locale('en', 'US').currency_formats['accounting']
1714 <NumberPattern u'\xa4#,##0.00;(\xa4#,##0.00)'>
1715
1716 property currency_symbols
1717 Mapping of currency codes to symbols.
1718
1719 >>> Locale('en', 'US').currency_symbols['USD']
1720 u'$'
1721 >>> Locale('es', 'CO').currency_symbols['USD']
1722 u'US$'
1723
1724 property date_formats
1725 Locale patterns for date formatting.
1726
1727 NOTE:
1728 The format of the value returned may change between
1729 Babel versions.
1730
1731 >>> Locale('en', 'US').date_formats['short']
1732 <DateTimePattern u'M/d/yy'>
1733 >>> Locale('fr', 'FR').date_formats['long']
1734 <DateTimePattern u'd MMMM y'>
1735
1736 property datetime_formats
1737 Locale patterns for datetime formatting.
1738
1739 NOTE:
1740 The format of the value returned may change between
1741 Babel versions.
1742
1743 >>> Locale('en').datetime_formats['full']
1744 u"{1} 'at' {0}"
1745 >>> Locale('th').datetime_formats['medium']
1746 u'{1} {0}'
1747
1748 property datetime_skeletons
1749 Locale patterns for formatting parts of a datetime.
1750
1751 >>> Locale('en').datetime_skeletons['MEd']
1752 <DateTimePattern u'E, M/d'>
1753 >>> Locale('fr').datetime_skeletons['MEd']
1754 <DateTimePattern u'E dd/MM'>
1755 >>> Locale('fr').datetime_skeletons['H']
1756 <DateTimePattern u"HH 'h'">
1757
1758 property day_period_rules
1759 Day period rules for the locale. Used by get_period_id.
1760
1761 property day_periods
1762 Locale display names for various day periods (not neces‐
1763 sarily only AM/PM).
1764
1765 These are not meant to be used without the relevant
1766 day_period_rules.
1767
1768 property days
1769 Locale display names for weekdays.
1770
1771 >>> Locale('de', 'DE').days['format']['wide'][3]
1772 u'Donnerstag'
1773
1774 property decimal_formats
1775 Locale patterns for decimal number formatting.
1776
1777 NOTE:
1778 The format of the value returned may change between
1779 Babel versions.
1780
1781 >>> Locale('en', 'US').decimal_formats[None]
1782 <NumberPattern u'#,##0.###'>
1783
1784 classmethod default(category=None, aliases={'ar': 'ar_SY', 'bg':
1785 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 'da':
1786 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es':
1787 'es_ES', 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr':
1788 'fr_FR', 'gl': 'gl_ES', 'he': 'he_IL', 'hu': 'hu_HU', 'id':
1789 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 'ja': 'ja_JP', 'km':
1790 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk':
1791 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl':
1792 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk':
1793 'sk_SK', 'sl': 'sl_SI', 'sv': 'sv_SE', 'th': 'th_TH', 'tr':
1794 'tr_TR', 'uk': 'uk_UA'})
1795 Return the system default locale for the specified cate‐
1796 gory.
1797
1798 >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
1799 ... os.environ[name] = ''
1800 >>> os.environ['LANG'] = 'fr_FR.UTF-8'
1801 >>> Locale.default('LC_MESSAGES')
1802 Locale('fr', territory='FR')
1803
1804 The following fallbacks to the variable are always con‐
1805 sidered:
1806
1807 • LANGUAGE
1808
1809 • LC_ALL
1810
1811 • LC_CTYPE
1812
1813 • LANG
1814
1815 Parameters
1816
1817 • category – one of the LC_XXX environment vari‐
1818 able names
1819
1820 • aliases – a dictionary of aliases for locale
1821 identifiers
1822
1823 property display_name
1824 The localized display name of the locale.
1825
1826 >>> Locale('en').display_name
1827 u'English'
1828 >>> Locale('en', 'US').display_name
1829 u'English (United States)'
1830 >>> Locale('sv').display_name
1831 u'svenska'
1832
1833 Type unicode
1834
1835 property english_name
1836 The english display name of the locale.
1837
1838 >>> Locale('de').english_name
1839 u'German'
1840 >>> Locale('de', 'DE').english_name
1841 u'German (Germany)'
1842
1843 Type unicode
1844
1845 property eras
1846 Locale display names for eras.
1847
1848 NOTE:
1849 The format of the value returned may change between
1850 Babel versions.
1851
1852 >>> Locale('en', 'US').eras['wide'][1]
1853 u'Anno Domini'
1854 >>> Locale('en', 'US').eras['abbreviated'][0]
1855 u'BC'
1856
1857 property first_week_day
1858 The first day of a week, with 0 being Monday.
1859
1860 >>> Locale('de', 'DE').first_week_day
1861 0
1862 >>> Locale('en', 'US').first_week_day
1863 6
1864
1865 get_display_name(locale=None)
1866 Return the display name of the locale using the given lo‐
1867 cale.
1868
1869 The display name will include the language, territory,
1870 script, and variant, if those are specified.
1871
1872 >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
1873 u'Chinese (Simplified, China)'
1874
1875 Parameters
1876 locale – the locale to use
1877
1878 get_language_name(locale=None)
1879 Return the language of this locale in the given locale.
1880
1881 >>> Locale('zh', 'CN', script='Hans').get_language_name('de')
1882 u'Chinesisch'
1883
1884 New in version 1.0.
1885
1886
1887 Parameters
1888 locale – the locale to use
1889
1890 get_script_name(locale=None)
1891 Return the script name in the given locale.
1892
1893 get_territory_name(locale=None)
1894 Return the territory name in the given locale.
1895
1896 property interval_formats
1897 Locale patterns for interval formatting.
1898
1899 NOTE:
1900 The format of the value returned may change between
1901 Babel versions.
1902
1903 How to format date intervals in Finnish when the day is
1904 the smallest changing component:
1905
1906 >>> Locale('fi_FI').interval_formats['MEd']['d']
1907 [u'E d. – ', u'E d.M.']
1908
1909 SEE ALSO:
1910 The primary API to use this data is
1911 babel.dates.format_interval().
1912
1913 Return type
1914 dict[str, dict[str, list[str]]]
1915
1916 language
1917 the language code
1918
1919 property language_name
1920 The localized language name of the locale.
1921
1922 >>> Locale('en', 'US').language_name
1923 u'English'
1924
1925 property languages
1926 Mapping of language codes to translated language names.
1927
1928 >>> Locale('de', 'DE').languages['ja']
1929 u'Japanisch'
1930
1931 See ISO 639 for more information.
1932
1933 property list_patterns
1934 Patterns for generating lists
1935
1936 NOTE:
1937 The format of the value returned may change between
1938 Babel versions.
1939
1940 >>> Locale('en').list_patterns['standard']['start']
1941 u'{0}, {1}'
1942 >>> Locale('en').list_patterns['standard']['end']
1943 u'{0}, and {1}'
1944 >>> Locale('en_GB').list_patterns['standard']['end']
1945 u'{0} and {1}'
1946
1947 property measurement_systems
1948 Localized names for various measurement systems.
1949
1950 >>> Locale('fr', 'FR').measurement_systems['US']
1951 u'am\xe9ricain'
1952 >>> Locale('en', 'US').measurement_systems['US']
1953 u'US'
1954
1955 property meta_zones
1956 Locale display names for meta time zones.
1957
1958 Meta time zones are basically groups of different Olson
1959 time zones that have the same GMT offset and daylight
1960 savings time.
1961
1962 NOTE:
1963 The format of the value returned may change between
1964 Babel versions.
1965
1966 >>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
1967 u'Central European Summer Time'
1968
1969 New in version 0.9.
1970
1971
1972 property min_week_days
1973 The minimum number of days in a week so that the week is
1974 counted as the first week of a year or month.
1975
1976 >>> Locale('de', 'DE').min_week_days
1977 4
1978
1979 property months
1980 Locale display names for months.
1981
1982 >>> Locale('de', 'DE').months['format']['wide'][10]
1983 u'Oktober'
1984
1985 classmethod negotiate(preferred, available, sep='_',
1986 aliases={'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca':
1987 'ca_ES', 'cs': 'cs_CZ', 'da': 'da_DK', 'de': 'de_DE', 'el':
1988 'el_GR', 'en': 'en_US', 'es': 'es_ES', 'et': 'et_EE', 'fa':
1989 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES', 'he':
1990 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it':
1991 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt':
1992 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn':
1993 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro':
1994 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv':
1995 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'})
1996 Find the best match between available and requested lo‐
1997 cale strings.
1998
1999 >>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
2000 Locale('de', territory='DE')
2001 >>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
2002 Locale('de')
2003 >>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
2004
2005 You can specify the character used in the locale identi‐
2006 fiers to separate the differnet components. This separa‐
2007 tor is applied to both lists. Also, case is ignored in
2008 the comparison:
2009
2010 >>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
2011 Locale('de', territory='DE')
2012
2013 Parameters
2014
2015 • preferred – the list of locale identifers pre‐
2016 ferred by the user
2017
2018 • available – the list of locale identifiers
2019 available
2020
2021 • aliases – a dictionary of aliases for locale
2022 identifiers
2023
2024 property number_symbols
2025 Symbols used in number formatting.
2026
2027 NOTE:
2028 The format of the value returned may change between
2029 Babel versions.
2030
2031 >>> Locale('fr', 'FR').number_symbols['decimal']
2032 u','
2033
2034 property ordinal_form
2035 Plural rules for the locale.
2036
2037 >>> Locale('en').ordinal_form(1)
2038 'one'
2039 >>> Locale('en').ordinal_form(2)
2040 'two'
2041 >>> Locale('en').ordinal_form(3)
2042 'few'
2043 >>> Locale('fr').ordinal_form(2)
2044 'other'
2045 >>> Locale('ru').ordinal_form(100)
2046 'other'
2047
2048 classmethod parse(identifier, sep='_', resolve_likely_sub‐
2049 tags=True)
2050 Create a Locale instance for the given locale identifier.
2051
2052 >>> l = Locale.parse('de-DE', sep='-')
2053 >>> l.display_name
2054 u'Deutsch (Deutschland)'
2055
2056 If the identifier parameter is not a string, but actually
2057 a Locale object, that object is returned:
2058
2059 >>> Locale.parse(l)
2060 Locale('de', territory='DE')
2061
2062 This also can perform resolving of likely subtags which
2063 it does by default. This is for instance useful to fig‐
2064 ure out the most likely locale for a territory you can
2065 use 'und' as the language tag:
2066
2067 >>> Locale.parse('und_AT')
2068 Locale('de', territory='AT')
2069
2070 Parameters
2071
2072 • identifier – the locale identifier string
2073
2074 • sep – optional component separator
2075
2076 • resolve_likely_subtags – if this is specified
2077 then a locale will have its likely subtag re‐
2078 solved if the locale otherwise does not exist.
2079 For instance zh_TW by itself is not a locale
2080 that exists but Babel can automatically expand
2081 it to the full form of zh_hant_TW. Note that
2082 this expansion is only taking place if no locale
2083 exists otherwise. For instance there is a lo‐
2084 cale en that can exist by itself.
2085
2086 Raises
2087
2088 • ValueError – if the string does not appear to be
2089 a valid locale identifier
2090
2091 • UnknownLocaleError – if no locale data is avail‐
2092 able for the requested locale
2093
2094 property percent_formats
2095 Locale patterns for percent number formatting.
2096
2097 NOTE:
2098 The format of the value returned may change between
2099 Babel versions.
2100
2101 >>> Locale('en', 'US').percent_formats[None]
2102 <NumberPattern u'#,##0%'>
2103
2104 property periods
2105 Locale display names for day periods (AM/PM).
2106
2107 >>> Locale('en', 'US').periods['am']
2108 u'AM'
2109
2110 property plural_form
2111 Plural rules for the locale.
2112
2113 >>> Locale('en').plural_form(1)
2114 'one'
2115 >>> Locale('en').plural_form(0)
2116 'other'
2117 >>> Locale('fr').plural_form(0)
2118 'one'
2119 >>> Locale('ru').plural_form(100)
2120 'many'
2121
2122 property quarters
2123 Locale display names for quarters.
2124
2125 >>> Locale('de', 'DE').quarters['format']['wide'][1]
2126 u'1. Quartal'
2127
2128 property scientific_formats
2129 Locale patterns for scientific number formatting.
2130
2131 NOTE:
2132 The format of the value returned may change between
2133 Babel versions.
2134
2135 >>> Locale('en', 'US').scientific_formats[None]
2136 <NumberPattern u'#E0'>
2137
2138 script the script code
2139
2140 property script_name
2141 The localized script name of the locale if available.
2142
2143 >>> Locale('sr', 'ME', script='Latn').script_name
2144 u'latinica'
2145
2146 property scripts
2147 Mapping of script codes to translated script names.
2148
2149 >>> Locale('en', 'US').scripts['Hira']
2150 u'Hiragana'
2151
2152 See ISO 15924 for more information.
2153
2154 property territories
2155 Mapping of script codes to translated script names.
2156
2157 >>> Locale('es', 'CO').territories['DE']
2158 u'Alemania'
2159
2160 See ISO 3166 for more information.
2161
2162 territory
2163 the territory (country or region) code
2164
2165 property territory_name
2166 The localized territory name of the locale if available.
2167
2168 >>> Locale('de', 'DE').territory_name
2169 u'Deutschland'
2170
2171 property text_direction
2172 The text direction for the language in CSS short-hand
2173 form.
2174
2175 >>> Locale('de', 'DE').text_direction
2176 'ltr'
2177 >>> Locale('ar', 'SA').text_direction
2178 'rtl'
2179
2180 property time_formats
2181 Locale patterns for time formatting.
2182
2183 NOTE:
2184 The format of the value returned may change between
2185 Babel versions.
2186
2187 >>> Locale('en', 'US').time_formats['short']
2188 <DateTimePattern u'h:mm a'>
2189 >>> Locale('fr', 'FR').time_formats['long']
2190 <DateTimePattern u'HH:mm:ss z'>
2191
2192 property time_zones
2193 Locale display names for time zones.
2194
2195 NOTE:
2196 The format of the value returned may change between
2197 Babel versions.
2198
2199 >>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
2200 u'British Summer Time'
2201 >>> Locale('en', 'US').time_zones['America/St_Johns']['city']
2202 u'St. John’s'
2203
2204 property unit_display_names
2205 Display names for units of measurement.
2206
2207 SEE ALSO:
2208 You may want to use babel.units.get_unit_name() in‐
2209 stead.
2210
2211 NOTE:
2212 The format of the value returned may change between
2213 Babel versions.
2214
2215 variant
2216 the variant code
2217
2218 property variants
2219 Mapping of script codes to translated script names.
2220
2221 >>> Locale('de', 'DE').variants['1901']
2222 u'Alte deutsche Rechtschreibung'
2223
2224 property weekend_end
2225 The day the weekend ends, with 0 being Monday.
2226
2227 >>> Locale('de', 'DE').weekend_end
2228 6
2229
2230 property weekend_start
2231 The day the weekend starts, with 0 being Monday.
2232
2233 >>> Locale('de', 'DE').weekend_start
2234 5
2235
2236 property zone_formats
2237 Patterns related to the formatting of time zones.
2238
2239 NOTE:
2240 The format of the value returned may change between
2241 Babel versions.
2242
2243 >>> Locale('en', 'US').zone_formats['fallback']
2244 u'%(1)s (%(0)s)'
2245 >>> Locale('pt', 'BR').zone_formats['region']
2246 u'Hor\xe1rio %s'
2247
2248 New in version 0.9.
2249
2250
2251 babel.core.default_locale(category=None, aliases={'ar': 'ar_SY', 'bg':
2252 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 'da': 'da_DK',
2253 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES', 'et':
2254 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
2255 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it':
2256 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT',
2257 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no':
2258 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU',
2259 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv': 'sv_SE', 'th': 'th_TH', 'tr':
2260 'tr_TR', 'uk': 'uk_UA'})
2261 Returns the system default locale for a given category, based on
2262 environment variables.
2263
2264 >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
2265 ... os.environ[name] = ''
2266 >>> os.environ['LANG'] = 'fr_FR.UTF-8'
2267 >>> default_locale('LC_MESSAGES')
2268 'fr_FR'
2269
2270 The “C” or “POSIX” pseudo-locales are treated as aliases for the
2271 “en_US_POSIX” locale:
2272
2273 >>> os.environ['LC_MESSAGES'] = 'POSIX'
2274 >>> default_locale('LC_MESSAGES')
2275 'en_US_POSIX'
2276
2277 The following fallbacks to the variable are always considered:
2278
2279 • LANGUAGE
2280
2281 • LC_ALL
2282
2283 • LC_CTYPE
2284
2285 • LANG
2286
2287 Parameters
2288
2289 • category – one of the LC_XXX environment variable names
2290
2291 • aliases – a dictionary of aliases for locale identi‐
2292 fiers
2293
2294 babel.core.negotiate_locale(preferred, available, sep='_',
2295 aliases={'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES',
2296 'cs': 'cs_CZ', 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en':
2297 'en_US', 'es': 'es_ES', 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI',
2298 'fr': 'fr_FR', 'gl': 'gl_ES', 'he': 'he_IL', 'hu': 'hu_HU', 'id':
2299 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH',
2300 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl':
2301 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT',
2302 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv':
2303 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'})
2304 Find the best match between available and requested locale
2305 strings.
2306
2307 >>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
2308 'de_DE'
2309 >>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
2310 'de'
2311
2312 Case is ignored by the algorithm, the result uses the case of
2313 the preferred locale identifier:
2314
2315 >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
2316 'de_DE'
2317
2318 >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
2319 'de_DE'
2320
2321 By default, some web browsers unfortunately do not include the
2322 territory in the locale identifier for many locales, and some
2323 don’t even allow the user to easily add the territory. So while
2324 you may prefer using qualified locale identifiers in your
2325 web-application, they would not normally match the language-only
2326 locale sent by such browsers. To workaround that, this function
2327 uses a default mapping of commonly used language-only locale
2328 identifiers to identifiers including the territory:
2329
2330 >>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
2331 'ja_JP'
2332
2333 Some browsers even use an incorrect or outdated language code,
2334 such as “no” for Norwegian, where the correct locale identifier
2335 would actually be “nb_NO” (Bokmål) or “nn_NO” (Nynorsk). The
2336 aliases are intended to take care of such cases, too:
2337
2338 >>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
2339 'nb_NO'
2340
2341 You can override this default mapping by passing a different
2342 aliases dictionary to this function, or you can bypass the be‐
2343 havior althogher by setting the aliases parameter to None.
2344
2345 Parameters
2346
2347 • preferred – the list of locale strings preferred by the
2348 user
2349
2350 • available – the list of locale strings available
2351
2352 • sep – character that separates the different parts of
2353 the locale strings
2354
2355 • aliases – a dictionary of aliases for locale identi‐
2356 fiers
2357
2358 Exceptions
2359 exception babel.core.UnknownLocaleError(identifier)
2360 Exception thrown when a locale is requested for which no locale
2361 data is available.
2362
2363 identifier
2364 The identifier of the locale that could not be found.
2365
2366 Utility Functions
2367 babel.core.get_global(key)
2368 Return the dictionary for the given key in the global data.
2369
2370 The global data is stored in the babel/global.dat file and con‐
2371 tains information independent of individual locales.
2372
2373 >>> get_global('zone_aliases')['UTC']
2374 u'Etc/UTC'
2375 >>> get_global('zone_territories')['Europe/Berlin']
2376 u'DE'
2377
2378 The keys available are:
2379
2380 • all_currencies
2381
2382 • currency_fractions
2383
2384 • language_aliases
2385
2386 • likely_subtags
2387
2388 • parent_exceptions
2389
2390 • script_aliases
2391
2392 • territory_aliases
2393
2394 • territory_currencies
2395
2396 • territory_languages
2397
2398 • territory_zones
2399
2400 • variant_aliases
2401
2402 • windows_zone_mapping
2403
2404 • zone_aliases
2405
2406 • zone_territories
2407
2408 NOTE:
2409 The internal structure of the data may change between ver‐
2410 sions.
2411
2412 New in version 0.9.
2413
2414
2415 Parameters
2416 key – the data key
2417
2418 babel.core.parse_locale(identifier, sep='_')
2419 Parse a locale identifier into a tuple of the form (language,
2420 territory, script, variant).
2421
2422 >>> parse_locale('zh_CN')
2423 ('zh', 'CN', None, None)
2424 >>> parse_locale('zh_Hans_CN')
2425 ('zh', 'CN', 'Hans', None)
2426 >>> parse_locale('ca_es_valencia')
2427 ('ca', 'ES', None, 'VALENCIA')
2428 >>> parse_locale('en_150')
2429 ('en', '150', None, None)
2430 >>> parse_locale('en_us_posix')
2431 ('en', 'US', None, 'POSIX')
2432
2433 The default component separator is “_”, but a different separa‐
2434 tor can be specified using the sep parameter:
2435
2436 >>> parse_locale('zh-CN', sep='-')
2437 ('zh', 'CN', None, None)
2438
2439 If the identifier cannot be parsed into a locale, a ValueError
2440 exception is raised:
2441
2442 >>> parse_locale('not_a_LOCALE_String')
2443 Traceback (most recent call last):
2444 ...
2445 ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
2446
2447 Encoding information and locale modifiers are removed from the
2448 identifier:
2449
2450 >>> parse_locale('it_IT@euro')
2451 ('it', 'IT', None, None)
2452 >>> parse_locale('en_US.UTF-8')
2453 ('en', 'US', None, None)
2454 >>> parse_locale('de_DE.iso885915@euro')
2455 ('de', 'DE', None, None)
2456
2457 See RFC 4646 for more information.
2458
2459 Parameters
2460
2461 • identifier – the locale identifier string
2462
2463 • sep – character that separates the different components
2464 of the locale identifier
2465
2466 Raises ValueError – if the string does not appear to be a valid
2467 locale identifier
2468
2469 babel.core.get_locale_identifier(tup, sep='_')
2470 The reverse of parse_locale(). It creates a locale identifier
2471 out of a (language, territory, script, variant) tuple. Items
2472 can be set to None and trailing Nones can also be left out of
2473 the tuple.
2474
2475 >>> get_locale_identifier(('de', 'DE', None, '1999'))
2476 'de_DE_1999'
2477
2478 New in version 1.0.
2479
2480
2481 Parameters
2482
2483 • tup – the tuple as returned by parse_locale().
2484
2485 • sep – the separator for the identifier.
2486
2487 Date and Time
2488 The date and time functionality provided by Babel lets you format stan‐
2489 dard Python datetime, date and time objects and work with timezones.
2490
2491 Date and Time Formatting
2492 babel.dates.format_datetime(datetime=None, format='medium', tz‐
2493 info=None, locale=default_locale('LC_TIME'))
2494 Return a date formatted according to the given pattern.
2495
2496 >>> dt = datetime(2007, 4, 1, 15, 30)
2497 >>> format_datetime(dt, locale='en_US')
2498 u'Apr 1, 2007, 3:30:00 PM'
2499
2500 For any pattern requiring the display of the time-zone, the
2501 third-party pytz package is needed to explicitly specify the
2502 time-zone:
2503
2504 >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
2505 ... locale='fr_FR')
2506 u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
2507 >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
2508 ... tzinfo=get_timezone('US/Eastern'), locale='en')
2509 u'2007.04.01 AD at 11:30:00 EDT'
2510
2511 Parameters
2512
2513 • datetime – the datetime object; if None, the current
2514 date and time is used
2515
2516 • format – one of “full”, “long”, “medium”, or “short”,
2517 or a custom date/time pattern
2518
2519 • tzinfo – the timezone to apply to the time for display
2520
2521 • locale – a Locale object or a locale identifier
2522
2523 babel.dates.format_date(date=None, format='medium', locale=default_lo‐
2524 cale('LC_TIME'))
2525 Return a date formatted according to the given pattern.
2526
2527 >>> d = date(2007, 4, 1)
2528 >>> format_date(d, locale='en_US')
2529 u'Apr 1, 2007'
2530 >>> format_date(d, format='full', locale='de_DE')
2531 u'Sonntag, 1. April 2007'
2532
2533 If you don’t want to use the locale default formats, you can
2534 specify a custom date pattern:
2535
2536 >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
2537 u"Sun, Apr 1, '07"
2538
2539 Parameters
2540
2541 • date – the date or datetime object; if None, the cur‐
2542 rent date is used
2543
2544 • format – one of “full”, “long”, “medium”, or “short”,
2545 or a custom date/time pattern
2546
2547 • locale – a Locale object or a locale identifier
2548
2549 babel.dates.format_time(time=None, format='medium', tzinfo=None, lo‐
2550 cale=default_locale('LC_TIME'))
2551 Return a time formatted according to the given pattern.
2552
2553 >>> t = time(15, 30)
2554 >>> format_time(t, locale='en_US')
2555 u'3:30:00 PM'
2556 >>> format_time(t, format='short', locale='de_DE')
2557 u'15:30'
2558
2559 If you don’t want to use the locale default formats, you can
2560 specify a custom time pattern:
2561
2562 >>> format_time(t, "hh 'o''clock' a", locale='en')
2563 u"03 o'clock PM"
2564
2565 For any pattern requiring the display of the time-zone a time‐
2566 zone has to be specified explicitly:
2567
2568 >>> t = datetime(2007, 4, 1, 15, 30)
2569 >>> tzinfo = get_timezone('Europe/Paris')
2570 >>> t = tzinfo.localize(t)
2571 >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
2572 u'15:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
2573 >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
2574 ... locale='en')
2575 u"09 o'clock AM, Eastern Daylight Time"
2576
2577 As that example shows, when this function gets passed a date‐
2578 time.datetime value, the actual time in the formatted string is
2579 adjusted to the timezone specified by the tzinfo parameter. If
2580 the datetime is “naive” (i.e. it has no associated timezone in‐
2581 formation), it is assumed to be in UTC.
2582
2583 These timezone calculations are not performed if the value is of
2584 type datetime.time, as without date information there’s no way
2585 to determine what a given time would translate to in a different
2586 timezone without information about whether daylight savings time
2587 is in effect or not. This means that time values are left as-is,
2588 and the value of the tzinfo parameter is only used to display
2589 the timezone name if needed:
2590
2591 >>> t = time(15, 30)
2592 >>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
2593 ... locale='fr_FR')
2594 u'15:30:00 heure normale d\u2019Europe centrale'
2595 >>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
2596 ... locale='en_US')
2597 u'3:30:00 PM Eastern Standard Time'
2598
2599 Parameters
2600
2601 • time – the time or datetime object; if None, the cur‐
2602 rent time in UTC is used
2603
2604 • format – one of “full”, “long”, “medium”, or “short”,
2605 or a custom date/time pattern
2606
2607 • tzinfo – the time-zone to apply to the time for display
2608
2609 • locale – a Locale object or a locale identifier
2610
2611 babel.dates.format_timedelta(delta, granularity='second', thresh‐
2612 old=.85, add_direction=False, format='long', locale=default_lo‐
2613 cale('LC_TIME'))
2614 Return a time delta according to the rules of the given locale.
2615
2616 >>> format_timedelta(timedelta(weeks=12), locale='en_US')
2617 u'3 months'
2618 >>> format_timedelta(timedelta(seconds=1), locale='es')
2619 u'1 segundo'
2620
2621 The granularity parameter can be provided to alter the lowest
2622 unit presented, which defaults to a second.
2623
2624 >>> format_timedelta(timedelta(hours=3), granularity='day',
2625 ... locale='en_US')
2626 u'1 day'
2627
2628 The threshold parameter can be used to determine at which value
2629 the presentation switches to the next higher unit. A higher
2630 threshold factor means the presentation will switch later. For
2631 example:
2632
2633 >>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
2634 u'1 day'
2635 >>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
2636 u'23 hours'
2637
2638 In addition directional information can be provided that informs
2639 the user if the date is in the past or in the future:
2640
2641 >>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
2642 u'in 1 hour'
2643 >>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
2644 u'1 hour ago'
2645
2646 The format parameter controls how compact or wide the presenta‐
2647 tion is:
2648
2649 >>> format_timedelta(timedelta(hours=3), format='short', locale='en')
2650 u'3 hr'
2651 >>> format_timedelta(timedelta(hours=3), format='narrow', locale='en')
2652 u'3h'
2653
2654 Parameters
2655
2656 • delta – a timedelta object representing the time dif‐
2657 ference to format, or the delta in seconds as an int
2658 value
2659
2660 • granularity – determines the smallest unit that should
2661 be displayed, the value can be one of “year”, “month”,
2662 “week”, “day”, “hour”, “minute” or “second”
2663
2664 • threshold – factor that determines at which point the
2665 presentation switches to the next higher unit
2666
2667 • add_direction – if this flag is set to True the return
2668 value will include directional information. For in‐
2669 stance a positive timedelta will include the informa‐
2670 tion about it being in the future, a negative will be
2671 information about the value being in the past.
2672
2673 • format – the format, can be “narrow”, “short” or
2674 “long”. ( “medium” is deprecated, currently converted
2675 to “long” to maintain compatibility)
2676
2677 • locale – a Locale object or a locale identifier
2678
2679 babel.dates.format_skeleton(skeleton, datetime=None, tzinfo=None,
2680 fuzzy=True, locale=default_locale('LC_TIME'))
2681 Return a time and/or date formatted according to the given pat‐
2682 tern.
2683
2684 The skeletons are defined in the CLDR data and provide more
2685 flexibility than the simple short/long/medium formats, but are a
2686 bit harder to use. The are defined using the date/time symbols
2687 without order or punctuation and map to a suitable format for
2688 the given locale.
2689
2690 >>> t = datetime(2007, 4, 1, 15, 30)
2691 >>> format_skeleton('MMMEd', t, locale='fr')
2692 u'dim. 1 avr.'
2693 >>> format_skeleton('MMMEd', t, locale='en')
2694 u'Sun, Apr 1'
2695 >>> format_skeleton('yMMd', t, locale='fi') # yMMd is not in the Finnish locale; yMd gets used
2696 u'1.4.2007'
2697 >>> format_skeleton('yMMd', t, fuzzy=False, locale='fi') # yMMd is not in the Finnish locale, an error is thrown
2698 Traceback (most recent call last):
2699 ...
2700 KeyError: yMMd
2701
2702 After the skeleton is resolved to a pattern format_datetime is
2703 called so all timezone processing etc is the same as for that.
2704
2705 Parameters
2706
2707 • skeleton – A date time skeleton as defined in the cldr
2708 data.
2709
2710 • datetime – the time or datetime object; if None, the
2711 current time in UTC is used
2712
2713 • tzinfo – the time-zone to apply to the time for display
2714
2715 • fuzzy – If the skeleton is not found, allow choosing a
2716 skeleton that’s close enough to it.
2717
2718 • locale – a Locale object or a locale identifier
2719
2720 babel.dates.format_interval(start, end, skeleton=None, tzinfo=None,
2721 fuzzy=True, locale=default_locale('LC_TIME'))
2722 Format an interval between two instants according to the lo‐
2723 cale’s rules.
2724
2725 >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
2726 u'15.–17.1.2016'
2727
2728 >>> format_interval(time(12, 12), time(16, 16), "Hm", locale="en_GB")
2729 '12:12–16:16'
2730
2731 >>> format_interval(time(5, 12), time(16, 16), "hm", locale="en_US")
2732 '5:12 AM – 4:16 PM'
2733
2734 >>> format_interval(time(16, 18), time(16, 24), "Hm", locale="it")
2735 '16:18–16:24'
2736
2737 If the start instant equals the end instant, the interval is
2738 formatted like the instant.
2739
2740 >>> format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
2741 '16:18'
2742
2743 Unknown skeletons fall back to “default” formatting.
2744
2745 >>> format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
2746 '2015/01/01~2017/01/01'
2747
2748 >>> format_interval(time(16, 18), time(16, 24), "xxx", locale="ja")
2749 '16:18:00~16:24:00'
2750
2751 >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
2752 '15.01.2016 – 17.01.2016'
2753
2754 Parameters
2755
2756 • start – First instant (datetime/date/time)
2757
2758 • end – Second instant (datetime/date/time)
2759
2760 • skeleton – The “skeleton format” to use for formatting.
2761
2762 • tzinfo – tzinfo to use (if none is already attached)
2763
2764 • fuzzy – If the skeleton is not found, allow choosing a
2765 skeleton that’s close enough to it.
2766
2767 • locale – A locale object or identifier.
2768
2769 Returns
2770 Formatted interval
2771
2772 Timezone Functionality
2773 babel.dates.get_timezone(zone=None)
2774 Looks up a timezone by name and returns it. The timezone object
2775 returned comes from pytz and corresponds to the tzinfo interface
2776 and can be used with all of the functions of Babel that operate
2777 with dates.
2778
2779 If a timezone is not known a LookupError is raised. If zone is
2780 None a local zone object is returned.
2781
2782 Parameters
2783 zone – the name of the timezone to look up. If a time‐
2784 zone object itself is passed in, mit’s returned un‐
2785 changed.
2786
2787 babel.dates.get_timezone_gmt(datetime=None, width='long', lo‐
2788 cale='en_US_POSIX', return_z=False)
2789 Return the timezone associated with the given datetime object
2790 formatted as string indicating the offset from GMT.
2791
2792 >>> dt = datetime(2007, 4, 1, 15, 30)
2793 >>> get_timezone_gmt(dt, locale='en')
2794 u'GMT+00:00'
2795 >>> get_timezone_gmt(dt, locale='en', return_z=True)
2796 'Z'
2797 >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
2798 u'+00'
2799 >>> tz = get_timezone('America/Los_Angeles')
2800 >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
2801 >>> get_timezone_gmt(dt, locale='en')
2802 u'GMT-07:00'
2803 >>> get_timezone_gmt(dt, 'short', locale='en')
2804 u'-0700'
2805 >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
2806 u'-07'
2807
2808 The long format depends on the locale, for example in France the
2809 acronym UTC string is used instead of GMT:
2810
2811 >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
2812 u'UTC-07:00'
2813
2814 New in version 0.9.
2815
2816
2817 Parameters
2818
2819 • datetime – the datetime object; if None, the current
2820 date and time in UTC is used
2821
2822 • width – either “long” or “short” or “iso8601” or
2823 “iso8601_short”
2824
2825 • locale – the Locale object, or a locale string
2826
2827 • return_z – True or False; Function returns indicator
2828 “Z” when local time offset is 0
2829
2830 babel.dates.get_timezone_location(dt_or_tzinfo=None, lo‐
2831 cale='en_US_POSIX', return_city=False)
2832 Return a representation of the given timezone using “location
2833 format”.
2834
2835 The result depends on both the local display name of the country
2836 and the city associated with the time zone:
2837
2838 >>> tz = get_timezone('America/St_Johns')
2839 >>> print(get_timezone_location(tz, locale='de_DE'))
2840 Kanada (St. John’s) Zeit
2841 >>> print(get_timezone_location(tz, locale='en'))
2842 Canada (St. John’s) Time
2843 >>> print(get_timezone_location(tz, locale='en', return_city=True))
2844 St. John’s
2845 >>> tz = get_timezone('America/Mexico_City')
2846 >>> get_timezone_location(tz, locale='de_DE')
2847 u'Mexiko (Mexiko-Stadt) Zeit'
2848
2849 If the timezone is associated with a country that uses only a
2850 single timezone, just the localized country name is returned:
2851
2852 >>> tz = get_timezone('Europe/Berlin')
2853 >>> get_timezone_name(tz, locale='de_DE')
2854 u'Mitteleurop\xe4ische Zeit'
2855
2856 New in version 0.9.
2857
2858
2859 Parameters
2860
2861 • dt_or_tzinfo – the datetime or tzinfo object that de‐
2862 termines the timezone; if None, the current date and
2863 time in UTC is assumed
2864
2865 • locale – the Locale object, or a locale string
2866
2867 • return_city – True or False, if True then return exem‐
2868 plar city (location) for the time zone
2869
2870 Returns
2871 the localized timezone name using location format
2872
2873 babel.dates.get_timezone_name(dt_or_tzinfo=None, width='long', uncom‐
2874 mon=False, locale='en_US_POSIX', zone_variant=None, return_zone=False)
2875 Return the localized display name for the given timezone. The
2876 timezone may be specified using a datetime or tzinfo object.
2877
2878 >>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
2879 >>> get_timezone_name(dt, locale='en_US')
2880 u'Pacific Standard Time'
2881 >>> get_timezone_name(dt, locale='en_US', return_zone=True)
2882 'America/Los_Angeles'
2883 >>> get_timezone_name(dt, width='short', locale='en_US')
2884 u'PST'
2885
2886 If this function gets passed only a tzinfo object and no con‐
2887 crete datetime, the returned display name is indenpendent of
2888 daylight savings time. This can be used for example for select‐
2889 ing timezones, or to set the time of events that recur across
2890 DST changes:
2891
2892 >>> tz = get_timezone('America/Los_Angeles')
2893 >>> get_timezone_name(tz, locale='en_US')
2894 u'Pacific Time'
2895 >>> get_timezone_name(tz, 'short', locale='en_US')
2896 u'PT'
2897
2898 If no localized display name for the timezone is available, and
2899 the timezone is associated with a country that uses only a sin‐
2900 gle timezone, the name of that country is returned, formatted
2901 according to the locale:
2902
2903 >>> tz = get_timezone('Europe/Berlin')
2904 >>> get_timezone_name(tz, locale='de_DE')
2905 u'Mitteleurop\xe4ische Zeit'
2906 >>> get_timezone_name(tz, locale='pt_BR')
2907 u'Hor\xe1rio da Europa Central'
2908
2909 On the other hand, if the country uses multiple timezones, the
2910 city is also included in the representation:
2911
2912 >>> tz = get_timezone('America/St_Johns')
2913 >>> get_timezone_name(tz, locale='de_DE')
2914 u'Neufundland-Zeit'
2915
2916 Note that short format is currently not supported for all time‐
2917 zones and all locales. This is partially because not every
2918 timezone has a short code in every locale. In that case it cur‐
2919 rently falls back to the long format.
2920
2921 For more information see LDML Appendix J: Time Zone Display
2922 Names
2923
2924 New in version 0.9.
2925
2926
2927 Changed in version 1.0: Added zone_variant support.
2928
2929
2930 Parameters
2931
2932 • dt_or_tzinfo – the datetime or tzinfo object that de‐
2933 termines the timezone; if a tzinfo object is used, the
2934 resulting display name will be generic, i.e. indepen‐
2935 dent of daylight savings time; if None, the current
2936 date in UTC is assumed
2937
2938 • width – either “long” or “short”
2939
2940 • uncommon – deprecated and ignored
2941
2942 • zone_variant – defines the zone variation to return.
2943 By default the variation is defined from the datetime
2944 object passed in. If no datetime object is passed in,
2945 the 'generic' variation is assumed. The following val‐
2946 ues are valid: 'generic', 'daylight' and 'standard'.
2947
2948 • locale – the Locale object, or a locale string
2949
2950 • return_zone – True or False. If true then function re‐
2951 turns long time zone ID
2952
2953 babel.dates.get_next_timezone_transition(zone=None, dt=None)
2954 Given a timezone it will return a TimezoneTransition object that
2955 holds the information about the next timezone transition that’s
2956 going to happen. For instance this can be used to detect when
2957 the next DST change is going to happen and how it looks like.
2958
2959 The transition is calculated relative to the given datetime ob‐
2960 ject. The next transition that follows the date is used. If a
2961 transition cannot be found the return value will be None.
2962
2963 Transition information can only be provided for timezones re‐
2964 turned by the get_timezone() function.
2965
2966 This function is pending deprecation with no replacement planned
2967 in the Babel library.
2968
2969 Parameters
2970
2971 • zone – the timezone for which the transition should be
2972 looked up. If not provided the local timezone is used.
2973
2974 • dt – the date after which the next transition should be
2975 found. If not given the current time is assumed.
2976
2977 babel.dates.UTC
2978 A timezone object for UTC.
2979
2980 babel.dates.LOCALTZ
2981 A timezone object for the computer’s local timezone.
2982
2983 class babel.dates.TimezoneTransition(activates, from_tzinfo, to_tzinfo,
2984 reference_date=None)
2985 A helper object that represents the return value from
2986 get_next_timezone_transition().
2987
2988 This class is pending deprecation with no replacement planned in
2989 the Babel library.
2990
2991 Field activates
2992 The time of the activation of the timezone transition in
2993 UTC.
2994
2995 Field from_tzinfo
2996 The timezone from where the transition starts.
2997
2998 Field to_tzinfo
2999 The timezone for after the transition.
3000
3001 Field reference_date
3002 The reference date that was provided. This is the dt pa‐
3003 rameter to the get_next_timezone_transition().
3004
3005 Data Access
3006 babel.dates.get_period_names(width='wide', context='stand-alone', lo‐
3007 cale='en_US_POSIX')
3008 Return the names for day periods (AM/PM) used by the locale.
3009
3010 >>> get_period_names(locale='en_US')['am']
3011 u'AM'
3012
3013 Parameters
3014
3015 • width – the width to use, one of “abbreviated”, “nar‐
3016 row”, or “wide”
3017
3018 • context – the context, either “format” or “stand-alone”
3019
3020 • locale – the Locale object, or a locale string
3021
3022 babel.dates.get_day_names(width='wide', context='format', lo‐
3023 cale='en_US_POSIX')
3024 Return the day names used by the locale for the specified for‐
3025 mat.
3026
3027 >>> get_day_names('wide', locale='en_US')[1]
3028 u'Tuesday'
3029 >>> get_day_names('short', locale='en_US')[1]
3030 u'Tu'
3031 >>> get_day_names('abbreviated', locale='es')[1]
3032 u'mar'
3033 >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
3034 u'D'
3035
3036 Parameters
3037
3038 • width – the width to use, one of “wide”, “abbreviated”,
3039 “short” or “narrow”
3040
3041 • context – the context, either “format” or “stand-alone”
3042
3043 • locale – the Locale object, or a locale string
3044
3045 babel.dates.get_month_names(width='wide', context='format', lo‐
3046 cale='en_US_POSIX')
3047 Return the month names used by the locale for the specified for‐
3048 mat.
3049
3050 >>> get_month_names('wide', locale='en_US')[1]
3051 u'January'
3052 >>> get_month_names('abbreviated', locale='es')[1]
3053 u'ene'
3054 >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
3055 u'J'
3056
3057 Parameters
3058
3059 • width – the width to use, one of “wide”, “abbreviated”,
3060 or “narrow”
3061
3062 • context – the context, either “format” or “stand-alone”
3063
3064 • locale – the Locale object, or a locale string
3065
3066 babel.dates.get_quarter_names(width='wide', context='format', lo‐
3067 cale='en_US_POSIX')
3068 Return the quarter names used by the locale for the specified
3069 format.
3070
3071 >>> get_quarter_names('wide', locale='en_US')[1]
3072 u'1st quarter'
3073 >>> get_quarter_names('abbreviated', locale='de_DE')[1]
3074 u'Q1'
3075 >>> get_quarter_names('narrow', locale='de_DE')[1]
3076 u'1'
3077
3078 Parameters
3079
3080 • width – the width to use, one of “wide”, “abbreviated”,
3081 or “narrow”
3082
3083 • context – the context, either “format” or “stand-alone”
3084
3085 • locale – the Locale object, or a locale string
3086
3087 babel.dates.get_era_names(width='wide', locale='en_US_POSIX')
3088 Return the era names used by the locale for the specified for‐
3089 mat.
3090
3091 >>> get_era_names('wide', locale='en_US')[1]
3092 u'Anno Domini'
3093 >>> get_era_names('abbreviated', locale='de_DE')[1]
3094 u'n. Chr.'
3095
3096 Parameters
3097
3098 • width – the width to use, either “wide”, “abbreviated”,
3099 or “narrow”
3100
3101 • locale – the Locale object, or a locale string
3102
3103 babel.dates.get_date_format(format='medium', locale='en_US_POSIX')
3104 Return the date formatting patterns used by the locale for the
3105 specified format.
3106
3107 >>> get_date_format(locale='en_US')
3108 <DateTimePattern u'MMM d, y'>
3109 >>> get_date_format('full', locale='de_DE')
3110 <DateTimePattern u'EEEE, d. MMMM y'>
3111
3112 Parameters
3113
3114 • format – the format to use, one of “full”, “long”,
3115 “medium”, or “short”
3116
3117 • locale – the Locale object, or a locale string
3118
3119 babel.dates.get_datetime_format(format='medium', locale='en_US_POSIX')
3120 Return the datetime formatting patterns used by the locale for
3121 the specified format.
3122
3123 >>> get_datetime_format(locale='en_US')
3124 u'{1}, {0}'
3125
3126 Parameters
3127
3128 • format – the format to use, one of “full”, “long”,
3129 “medium”, or “short”
3130
3131 • locale – the Locale object, or a locale string
3132
3133 babel.dates.get_time_format(format='medium', locale='en_US_POSIX')
3134 Return the time formatting patterns used by the locale for the
3135 specified format.
3136
3137 >>> get_time_format(locale='en_US')
3138 <DateTimePattern u'h:mm:ss a'>
3139 >>> get_time_format('full', locale='de_DE')
3140 <DateTimePattern u'HH:mm:ss zzzz'>
3141
3142 Parameters
3143
3144 • format – the format to use, one of “full”, “long”,
3145 “medium”, or “short”
3146
3147 • locale – the Locale object, or a locale string
3148
3149 Basic Parsing
3150 babel.dates.parse_date(string, locale='en_US_POSIX', format='medium')
3151 Parse a date from a string.
3152
3153 This function uses the date format for the locale as a hint to
3154 determine the order in which the date fields appear in the
3155 string.
3156
3157 >>> parse_date('4/1/04', locale='en_US')
3158 datetime.date(2004, 4, 1)
3159 >>> parse_date('01.04.2004', locale='de_DE')
3160 datetime.date(2004, 4, 1)
3161
3162 Parameters
3163
3164 • string – the string containing the date
3165
3166 • locale – a Locale object or a locale identifier
3167
3168 • format – the format to use (see get_date_format)
3169
3170 babel.dates.parse_time(string, locale='en_US_POSIX', format='medium')
3171 Parse a time from a string.
3172
3173 This function uses the time format for the locale as a hint to
3174 determine the order in which the time fields appear in the
3175 string.
3176
3177 >>> parse_time('15:30:00', locale='en_US')
3178 datetime.time(15, 30)
3179
3180 Parameters
3181
3182 • string – the string containing the time
3183
3184 • locale – a Locale object or a locale identifier
3185
3186 • format – the format to use (see get_time_format)
3187
3188 Returns
3189 the parsed time
3190
3191 Return type
3192 time
3193
3194 babel.dates.parse_pattern(pattern)
3195 Parse date, time, and datetime format patterns.
3196
3197 >>> parse_pattern("MMMMd").format
3198 u'%(MMMM)s%(d)s'
3199 >>> parse_pattern("MMM d, yyyy").format
3200 u'%(MMM)s %(d)s, %(yyyy)s'
3201
3202 Pattern can contain literal strings in single quotes:
3203
3204 >>> parse_pattern("H:mm' Uhr 'z").format
3205 u'%(H)s:%(mm)s Uhr %(z)s'
3206
3207 An actual single quote can be used by using two adjacent single
3208 quote characters:
3209
3210 >>> parse_pattern("hh' o''clock'").format
3211 u"%(hh)s o'clock"
3212
3213 Parameters
3214 pattern – the formatting pattern to parse
3215
3216 Languages
3217 The languages module provides functionality to access data about lan‐
3218 guages that is not bound to a given locale.
3219
3220 Official Languages
3221 babel.languages.get_official_languages(territory, regional=False,
3222 de_facto=False)
3223 Get the official language(s) for the given territory.
3224
3225 The language codes, if any are known, are returned in order of
3226 descending popularity.
3227
3228 If the regional flag is set, then languages which are regionally
3229 official are also returned.
3230
3231 If the de_facto flag is set, then languages which are “de facto”
3232 official are also returned.
3233
3234 WARNING:
3235 Note that the data is as up to date as the current version of
3236 the CLDR used by Babel. If you need scientifically accurate
3237 information, use another source!
3238
3239 Parameters
3240
3241 • territory (str) – Territory code
3242
3243 • regional (bool) – Whether to return regionally official
3244 languages too
3245
3246 • de_facto (bool) – Whether to return de-facto official
3247 languages too
3248
3249 Returns
3250 Tuple of language codes
3251
3252 Return type
3253 tuple[str]
3254
3255 babel.languages.get_territory_language_info(territory)
3256 Get a dictionary of language information for a territory.
3257
3258 The dictionary is keyed by language code; the values are dicts
3259 with more information.
3260
3261 The following keys are currently known for the values:
3262
3263 •
3264
3265 population_percent: The percentage of the territory’s popula‐
3266 tion speaking the
3267 language.
3268
3269 •
3270
3271 official_status: An optional string describing the officiality
3272 status of the language.
3273 Known values are “official”, “official_regional” and
3274 “de_facto_official”.
3275
3276 WARNING:
3277 Note that the data is as up to date as the current version of
3278 the CLDR used by Babel. If you need scientifically accurate
3279 information, use another source!
3280
3281 NOTE:
3282 Note that the format of the dict returned may change between
3283 Babel versions.
3284
3285 See
3286 https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
3287
3288 Parameters
3289 territory (str) – Territory code
3290
3291 Returns
3292 Language information dictionary
3293
3294 Return type
3295 dict[str, dict]
3296
3297 List Formatting
3298 This module lets you format lists of items in a locale-dependent man‐
3299 ner.
3300
3301 babel.lists.format_list(lst, style='standard', locale='en_US_POSIX')
3302 Format the items in lst as a list.
3303
3304 >>> format_list(['apples', 'oranges', 'pears'], locale='en')
3305 u'apples, oranges, and pears'
3306 >>> format_list(['apples', 'oranges', 'pears'], locale='zh')
3307 u'apples、oranges和pears'
3308 >>> format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
3309 u'omena, peruna tai aplari'
3310
3311 These styles are defined, but not all are necessarily available
3312 in all locales. The following text is verbatim from the Unicode
3313 TR35-49 spec [1].
3314
3315 • standard: A typical ‘and’ list for arbitrary placeholders.
3316 eg. “January, February, and March”
3317
3318 • standard-short: A short version of a ‘and’ list, suitable for
3319 use with short or abbreviated placeholder values. eg. “Jan.,
3320 Feb., and Mar.”
3321
3322 • or: A typical ‘or’ list for arbitrary placeholders. eg. “Jan‐
3323 uary, February, or March”
3324
3325 • or-short: A short version of an ‘or’ list. eg. “Jan., Feb.,
3326 or Mar.”
3327
3328 • unit: A list suitable for wide units. eg. “3 feet, 7 inches”
3329
3330 • unit-short: A list suitable for short units eg. “3 ft, 7 in”
3331
3332 • unit-narrow: A list suitable for narrow units, where space on
3333 the screen is very limited. eg. “3′ 7″”
3334
3335 [1]:
3336 https://www.unicode.org/reports/tr35/tr35-49/tr35-general.html#ListPatterns
3337
3338 Parameters
3339
3340 • lst – a sequence of items to format in to a list
3341
3342 • style – the style to format the list with. See above
3343 for description.
3344
3345 • locale – the locale
3346
3347 Messages and Catalogs
3348 Babel provides functionality to work with message catalogs. This part
3349 of the API documentation shows those parts.
3350
3351 Messages and Catalogs
3352 This module provides a basic interface to hold catalog and message in‐
3353 formation. It’s generally used to modify a gettext catalog but it is
3354 not being used to actually use the translations.
3355
3356 Catalogs
3357 class babel.messages.catalog.Catalog(locale=None, domain=None,
3358 header_comment='# Translations template for PROJECT.\n# Copyright (C)
3359 YEAR ORGANIZATION\n# This file is distributed under the same license as
3360 the PROJECT project.\n# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n#',
3361 project=None, version=None, copyright_holder=None, msgid_bugs_ad‐
3362 dress=None, creation_date=None, revision_date=None, last_transla‐
3363 tor=None, language_team=None, charset=None, fuzzy=True)
3364 Representation of a message catalog.
3365
3366 __iter__()
3367 Iterates through all the entries in the catalog, in the
3368 order they were added, yielding a Message object for ev‐
3369 ery entry.
3370
3371 Return type
3372 iterator
3373
3374 add(id, string=None, locations=(), flags=(), auto_comments=(),
3375 user_comments=(), previous_id=(), lineno=None, context=None)
3376 Add or update the message with the specified ID.
3377
3378 >>> catalog = Catalog()
3379 >>> catalog.add(u'foo')
3380 <Message ...>
3381 >>> catalog[u'foo']
3382 <Message u'foo' (flags: [])>
3383
3384 This method simply constructs a Message object with the
3385 given arguments and invokes __setitem__ with that object.
3386
3387 Parameters
3388
3389 • id – the message ID, or a (singular, plural) tu‐
3390 ple for pluralizable messages
3391
3392 • string – the translated message string, or a
3393 (singular, plural) tuple for pluralizable mes‐
3394 sages
3395
3396 • locations – a sequence of (filename, lineno) tu‐
3397 ples
3398
3399 • flags – a set or sequence of flags
3400
3401 • auto_comments – a sequence of automatic comments
3402
3403 • user_comments – a sequence of user comments
3404
3405 • previous_id – the previous message ID, or a
3406 (singular, plural) tuple for pluralizable mes‐
3407 sages
3408
3409 • lineno – the line number on which the msgid line
3410 was found in the PO file, if any
3411
3412 • context – the message context
3413
3414 check()
3415 Run various validation checks on the translations in the
3416 catalog.
3417
3418 For every message which fails validation, this method
3419 yield a (message, errors) tuple, where message is the
3420 Message object and errors is a sequence of Translation‐
3421 Error objects.
3422
3423 Return type
3424 iterator
3425
3426 delete(id, context=None)
3427 Delete the message with the specified ID and context.
3428
3429 Parameters
3430
3431 • id – the message ID
3432
3433 • context – the message context, or None for no
3434 context
3435
3436 get(id, context=None)
3437 Return the message with the specified ID and context.
3438
3439 Parameters
3440
3441 • id – the message ID
3442
3443 • context – the message context, or None for no
3444 context
3445
3446 property header_comment
3447 The header comment for the catalog.
3448
3449 >>> catalog = Catalog(project='Foobar', version='1.0',
3450 ... copyright_holder='Foo Company')
3451 >>> print(catalog.header_comment)
3452 # Translations template for Foobar.
3453 # Copyright (C) ... Foo Company
3454 # This file is distributed under the same license as the Foobar project.
3455 # FIRST AUTHOR <EMAIL@ADDRESS>, ....
3456 #
3457
3458 The header can also be set from a string. Any known up‐
3459 per-case variables will be replaced when the header is
3460 retrieved again:
3461
3462 >>> catalog = Catalog(project='Foobar', version='1.0',
3463 ... copyright_holder='Foo Company')
3464 >>> catalog.header_comment = '''\
3465 ... # The POT for my really cool PROJECT project.
3466 ... # Copyright (C) 1990-2003 ORGANIZATION
3467 ... # This file is distributed under the same license as the PROJECT
3468 ... # project.
3469 ... #'''
3470 >>> print(catalog.header_comment)
3471 # The POT for my really cool Foobar project.
3472 # Copyright (C) 1990-2003 Foo Company
3473 # This file is distributed under the same license as the Foobar
3474 # project.
3475 #
3476
3477 Type unicode
3478
3479 is_identical(other)
3480 Checks if catalogs are identical, taking into account
3481 messages and headers.
3482
3483 language_team
3484 Name and email address of the language team.
3485
3486 last_translator
3487 Name and email address of the last translator.
3488
3489 property mime_headers
3490 The MIME headers of the catalog, used for the special ms‐
3491 gid "" entry.
3492
3493 The behavior of this property changes slightly depending
3494 on whether a locale is set or not, the latter indicating
3495 that the catalog is actually a template for actual trans‐
3496 lations.
3497
3498 Here’s an example of the output for such a catalog tem‐
3499 plate:
3500
3501 >>> from babel.dates import UTC
3502 >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
3503 >>> catalog = Catalog(project='Foobar', version='1.0',
3504 ... creation_date=created)
3505 >>> for name, value in catalog.mime_headers:
3506 ... print('%s: %s' % (name, value))
3507 Project-Id-Version: Foobar 1.0
3508 Report-Msgid-Bugs-To: EMAIL@ADDRESS
3509 POT-Creation-Date: 1990-04-01 15:30+0000
3510 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
3511 Last-Translator: FULL NAME <EMAIL@ADDRESS>
3512 Language-Team: LANGUAGE <LL@li.org>
3513 MIME-Version: 1.0
3514 Content-Type: text/plain; charset=utf-8
3515 Content-Transfer-Encoding: 8bit
3516 Generated-By: Babel ...
3517
3518 And here’s an example of the output when the locale is
3519 set:
3520
3521 >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
3522 >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
3523 ... creation_date=created, revision_date=revised,
3524 ... last_translator='John Doe <jd@example.com>',
3525 ... language_team='de_DE <de@example.com>')
3526 >>> for name, value in catalog.mime_headers:
3527 ... print('%s: %s' % (name, value))
3528 Project-Id-Version: Foobar 1.0
3529 Report-Msgid-Bugs-To: EMAIL@ADDRESS
3530 POT-Creation-Date: 1990-04-01 15:30+0000
3531 PO-Revision-Date: 1990-08-03 12:00+0000
3532 Last-Translator: John Doe <jd@example.com>
3533 Language: de_DE
3534 Language-Team: de_DE <de@example.com>
3535 Plural-Forms: nplurals=2; plural=(n != 1);
3536 MIME-Version: 1.0
3537 Content-Type: text/plain; charset=utf-8
3538 Content-Transfer-Encoding: 8bit
3539 Generated-By: Babel ...
3540
3541 Type list
3542
3543 property num_plurals
3544 The number of plurals used by the catalog or locale.
3545
3546 >>> Catalog(locale='en').num_plurals
3547 2
3548 >>> Catalog(locale='ga').num_plurals
3549 5
3550
3551 Type int
3552
3553 property plural_expr
3554 The plural expression used by the catalog or locale.
3555
3556 >>> Catalog(locale='en').plural_expr
3557 '(n != 1)'
3558 >>> Catalog(locale='ga').plural_expr
3559 '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)'
3560 >>> Catalog(locale='ding').plural_expr # unknown locale
3561 '(n != 1)'
3562
3563 Type str
3564
3565 property plural_forms
3566 Return the plural forms declaration for the locale.
3567
3568 >>> Catalog(locale='en').plural_forms
3569 'nplurals=2; plural=(n != 1);'
3570 >>> Catalog(locale='pt_BR').plural_forms
3571 'nplurals=2; plural=(n > 1);'
3572
3573 Type str
3574
3575 update(template, no_fuzzy_matching=False, update_header_com‐
3576 ment=False, keep_user_comments=True)
3577 Update the catalog based on the given template catalog.
3578
3579 >>> from babel.messages import Catalog
3580 >>> template = Catalog()
3581 >>> template.add('green', locations=[('main.py', 99)])
3582 <Message ...>
3583 >>> template.add('blue', locations=[('main.py', 100)])
3584 <Message ...>
3585 >>> template.add(('salad', 'salads'), locations=[('util.py', 42)])
3586 <Message ...>
3587 >>> catalog = Catalog(locale='de_DE')
3588 >>> catalog.add('blue', u'blau', locations=[('main.py', 98)])
3589 <Message ...>
3590 >>> catalog.add('head', u'Kopf', locations=[('util.py', 33)])
3591 <Message ...>
3592 >>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'),
3593 ... locations=[('util.py', 38)])
3594 <Message ...>
3595
3596 >>> catalog.update(template)
3597 >>> len(catalog)
3598 3
3599
3600 >>> msg1 = catalog['green']
3601 >>> msg1.string
3602 >>> msg1.locations
3603 [('main.py', 99)]
3604
3605 >>> msg2 = catalog['blue']
3606 >>> msg2.string
3607 u'blau'
3608 >>> msg2.locations
3609 [('main.py', 100)]
3610
3611 >>> msg3 = catalog['salad']
3612 >>> msg3.string
3613 (u'Salat', u'Salate')
3614 >>> msg3.locations
3615 [('util.py', 42)]
3616
3617 Messages that are in the catalog but not in the template
3618 are removed from the main collection, but can still be
3619 accessed via the obsolete member:
3620
3621 >>> 'head' in catalog
3622 False
3623 >>> list(catalog.obsolete.values())
3624 [<Message 'head' (flags: [])>]
3625
3626 Parameters
3627
3628 • template – the reference catalog, usually read
3629 from a POT file
3630
3631 • no_fuzzy_matching – whether to use fuzzy match‐
3632 ing of message IDs
3633
3634 Messages
3635 class babel.messages.catalog.Message(id, string='', locations=(),
3636 flags=(), auto_comments=(), user_comments=(), previous_id=(),
3637 lineno=None, context=None)
3638 Representation of a single message in a catalog.
3639
3640 check(catalog=None)
3641 Run various validation checks on the message. Some vali‐
3642 dations are only performed if the catalog is provided.
3643 This method returns a sequence of TranslationError ob‐
3644 jects.
3645
3646 Return type
3647 iterator
3648
3649 Parameters
3650 catalog – A catalog instance that is passed to the
3651 checkers
3652
3653 See Catalog.check for a way to perform checks for all
3654 messages in a catalog.
3655
3656 property fuzzy
3657 Whether the translation is fuzzy.
3658
3659 >>> Message('foo').fuzzy
3660 False
3661 >>> msg = Message('foo', 'foo', flags=['fuzzy'])
3662 >>> msg.fuzzy
3663 True
3664 >>> msg
3665 <Message 'foo' (flags: ['fuzzy'])>
3666
3667 Type bool
3668
3669 is_identical(other)
3670 Checks whether messages are identical, taking into ac‐
3671 count all properties.
3672
3673 property pluralizable
3674 Whether the message is plurizable.
3675
3676 >>> Message('foo').pluralizable
3677 False
3678 >>> Message(('foo', 'bar')).pluralizable
3679 True
3680
3681 Type bool
3682
3683 property python_format
3684 Whether the message contains Python-style parameters.
3685
3686 >>> Message('foo %(name)s bar').python_format
3687 True
3688 >>> Message(('foo %(name)s', 'foo %(name)s')).python_format
3689 True
3690
3691 Type bool
3692
3693 Exceptions
3694 exception babel.messages.catalog.TranslationError
3695 Exception thrown by translation checkers when invalid message
3696 translations are encountered.
3697
3698 Low-Level Extraction Interface
3699 The low level extraction interface can be used to extract from directo‐
3700 ries or files directly. Normally this is not needed as the command
3701 line tools can do that for you.
3702
3703 Extraction Functions
3704 The extraction functions are what the command line tools use internally
3705 to extract strings.
3706
3707 babel.messages.extract.extract_from_dir(dirname=None,
3708 method_map=[('**.py', 'python')], options_map=None, keywords={'N_':
3709 None, '_': None, 'dgettext': (2,), 'dngettext': (2, 3), 'gettext':
3710 None, 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3), 'pgettext':
3711 ((1, 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, comment_tags=(),
3712 callback=None, strip_comment_tags=False, directory_filter=None)
3713 Extract messages from any source files found in the given direc‐
3714 tory.
3715
3716 This function generates tuples of the form (filename, lineno,
3717 message, comments, context).
3718
3719 Which extraction method is used per file is determined by the
3720 method_map parameter, which maps extended glob patterns to ex‐
3721 traction method names. For example, the following is the de‐
3722 fault mapping:
3723
3724 >>> method_map = [
3725 ... ('**.py', 'python')
3726 ... ]
3727
3728 This basically says that files with the filename extension “.py”
3729 at any level inside the directory should be processed by the
3730 “python” extraction method. Files that don’t match any of the
3731 mapping patterns are ignored. See the documentation of the path‐
3732 match function for details on the pattern syntax.
3733
3734 The following extended mapping would also use the “genshi” ex‐
3735 traction method on any file in “templates” subdirectory:
3736
3737 >>> method_map = [
3738 ... ('**/templates/**.*', 'genshi'),
3739 ... ('**.py', 'python')
3740 ... ]
3741
3742 The dictionary provided by the optional options_map parameter
3743 augments these mappings. It uses extended glob patterns as keys,
3744 and the values are dictionaries mapping options names to option
3745 values (both strings).
3746
3747 The glob patterns of the options_map do not necessarily need to
3748 be the same as those used in the method mapping. For example,
3749 while all files in the templates folders in an application may
3750 be Genshi applications, the options for those files may differ
3751 based on extension:
3752
3753 >>> options_map = {
3754 ... '**/templates/**.txt': {
3755 ... 'template_class': 'genshi.template:TextTemplate',
3756 ... 'encoding': 'latin-1'
3757 ... },
3758 ... '**/templates/**.html': {
3759 ... 'include_attrs': ''
3760 ... }
3761 ... }
3762
3763 Parameters
3764
3765 • dirname – the path to the directory to extract messages
3766 from. If not given the current working directory is
3767 used.
3768
3769 • method_map – a list of (pattern, method) tuples that
3770 maps of extraction method names to extended glob pat‐
3771 terns
3772
3773 • options_map – a dictionary of additional options (op‐
3774 tional)
3775
3776 • keywords – a dictionary mapping keywords (i.e. names of
3777 functions that should be recognized as translation
3778 functions) to tuples that specify which of their argu‐
3779 ments contain localizable strings
3780
3781 • comment_tags – a list of tags of translator comments to
3782 search for and include in the results
3783
3784 • callback – a function that is called for every file
3785 that message are extracted from, just before the ex‐
3786 traction itself is performed; the function is passed
3787 the filename, the name of the extraction method and and
3788 the options dictionary as positional arguments, in that
3789 order
3790
3791 • strip_comment_tags – a flag that if set to True causes
3792 all comment tags to be removed from the collected com‐
3793 ments.
3794
3795 • directory_filter – a callback to determine whether a
3796 directory should be recursed into. Receives the full
3797 directory path; should return True if the directory is
3798 valid.
3799
3800 See pathmatch
3801
3802 babel.messages.extract.extract_from_file(method, filename, key‐
3803 words={'N_': None, '_': None, 'dgettext': (2,), 'dngettext': (2, 3),
3804 'gettext': None, 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3),
3805 'pgettext': ((1, 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, com‐
3806 ment_tags=(), options=None, strip_comment_tags=False)
3807 Extract messages from a specific file.
3808
3809 This function returns a list of tuples of the form (lineno, mes‐
3810 sage, comments, context).
3811
3812 Parameters
3813
3814 • filename – the path to the file to extract messages
3815 from
3816
3817 • method – a string specifying the extraction method
3818 (.e.g. “python”)
3819
3820 • keywords – a dictionary mapping keywords (i.e. names of
3821 functions that should be recognized as translation
3822 functions) to tuples that specify which of their argu‐
3823 ments contain localizable strings
3824
3825 • comment_tags – a list of translator tags to search for
3826 and include in the results
3827
3828 • strip_comment_tags – a flag that if set to True causes
3829 all comment tags to be removed from the collected com‐
3830 ments.
3831
3832 • options – a dictionary of additional options (optional)
3833
3834 Returns
3835 list of tuples of the form (lineno, message, comments,
3836 context)
3837
3838 Return type
3839 list[tuple[int, str|tuple[str], list[str], str|None]
3840
3841 babel.messages.extract.extract(method, fileobj, keywords={'N_': None,
3842 '_': None, 'dgettext': (2,), 'dngettext': (2, 3), 'gettext': None,
3843 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3), 'pgettext': ((1,
3844 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, comment_tags=(), op‐
3845 tions=None, strip_comment_tags=False)
3846 Extract messages from the given file-like object using the spec‐
3847 ified extraction method.
3848
3849 This function returns tuples of the form (lineno, message, com‐
3850 ments, context).
3851
3852 The implementation dispatches the actual extraction to plugins,
3853 based on the value of the method parameter.
3854
3855 >>> source = b'''# foo module
3856 ... def run(argv):
3857 ... print(_('Hello, world!'))
3858 ... '''
3859
3860 >>> from io import BytesIO
3861 >>> for message in extract('python', BytesIO(source)):
3862 ... print(message)
3863 (3, u'Hello, world!', [], None)
3864
3865 Parameters
3866
3867 • method – an extraction method (a callable), or a string
3868 specifying the extraction method (.e.g. “python”); if
3869 this is a simple name, the extraction function will be
3870 looked up by entry point; if it is an explicit refer‐
3871 ence to a function (of the form package.module:funcname
3872 or package.module.funcname), the corresponding function
3873 will be imported and used
3874
3875 • fileobj – the file-like object the messages should be
3876 extracted from
3877
3878 • keywords – a dictionary mapping keywords (i.e. names of
3879 functions that should be recognized as translation
3880 functions) to tuples that specify which of their argu‐
3881 ments contain localizable strings
3882
3883 • comment_tags – a list of translator tags to search for
3884 and include in the results
3885
3886 • options – a dictionary of additional options (optional)
3887
3888 • strip_comment_tags – a flag that if set to True causes
3889 all comment tags to be removed from the collected com‐
3890 ments.
3891
3892 Raises ValueError – if the extraction method is not registered
3893
3894 Returns
3895 iterable of tuples of the form (lineno, message, com‐
3896 ments, context)
3897
3898 Return type
3899 Iterable[tuple[int, str|tuple[str], list[str], str|None]
3900
3901 Language Parsing
3902 The language parsing functions are used to extract strings out of
3903 source files. These are automatically being used by the extraction
3904 functions but sometimes it can be useful to register wrapper functions,
3905 then these low level functions can be invoked.
3906
3907 New functions can be registered through the setuptools entrypoint sys‐
3908 tem.
3909
3910 babel.messages.extract.extract_python(fileobj, keywords, comment_tags,
3911 options)
3912 Extract messages from Python source code.
3913
3914 It returns an iterator yielding tuples in the following form
3915 (lineno, funcname, message, comments).
3916
3917 Parameters
3918
3919 • fileobj – the seekable, file-like object the messages
3920 should be extracted from
3921
3922 • keywords – a list of keywords (i.e. function names)
3923 that should be recognized as translation functions
3924
3925 • comment_tags – a list of translator tags to search for
3926 and include in the results
3927
3928 • options – a dictionary of additional options (optional)
3929
3930 Return type
3931 iterator
3932
3933 babel.messages.extract.extract_javascript(fileobj, keywords, com‐
3934 ment_tags, options)
3935 Extract messages from JavaScript source code.
3936
3937 Parameters
3938
3939 • fileobj – the seekable, file-like object the messages
3940 should be extracted from
3941
3942 • keywords – a list of keywords (i.e. function names)
3943 that should be recognized as translation functions
3944
3945 • comment_tags – a list of translator tags to search for
3946 and include in the results
3947
3948 • options – a dictionary of additional options (optional)
3949 Supported options are: * jsx – set to false to disable
3950 JSX/E4X support. * template_string – set to false to
3951 disable ES6 template string support.
3952
3953 babel.messages.extract.extract_nothing(fileobj, keywords, comment_tags,
3954 options)
3955 Pseudo extractor that does not actually extract anything, but
3956 simply returns an empty list.
3957
3958 MO File Support
3959 The MO file support can read and write MO files. It reads them into
3960 Catalog objects and also writes catalogs out.
3961
3962 babel.messages.mofile.read_mo(fileobj)
3963 Read a binary MO file from the given file-like object and return
3964 a corresponding Catalog object.
3965
3966 Parameters
3967 fileobj – the file-like object to read the MO file from
3968
3969 Note The implementation of this function is heavily based on
3970 the GNUTranslations._parse method of the gettext module
3971 in the standard library.
3972
3973 babel.messages.mofile.write_mo(fileobj, catalog, use_fuzzy=False)
3974 Write a catalog to the specified file-like object using the GNU
3975 MO file format.
3976
3977 >>> import sys
3978 >>> from babel.messages import Catalog
3979 >>> from gettext import GNUTranslations
3980 >>> from io import BytesIO
3981
3982 >>> catalog = Catalog(locale='en_US')
3983 >>> catalog.add('foo', 'Voh')
3984 <Message ...>
3985 >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
3986 <Message ...>
3987 >>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
3988 <Message ...>
3989 >>> catalog.add('Fizz', '')
3990 <Message ...>
3991 >>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
3992 <Message ...>
3993 >>> buf = BytesIO()
3994
3995 >>> write_mo(buf, catalog)
3996 >>> x = buf.seek(0)
3997 >>> translations = GNUTranslations(fp=buf)
3998 >>> if sys.version_info[0] >= 3:
3999 ... translations.ugettext = translations.gettext
4000 ... translations.ungettext = translations.ngettext
4001 >>> translations.ugettext('foo')
4002 u'Voh'
4003 >>> translations.ungettext('bar', 'baz', 1)
4004 u'Bahr'
4005 >>> translations.ungettext('bar', 'baz', 2)
4006 u'Batz'
4007 >>> translations.ugettext('fuz')
4008 u'fuz'
4009 >>> translations.ugettext('Fizz')
4010 u'Fizz'
4011 >>> translations.ugettext('Fuzz')
4012 u'Fuzz'
4013 >>> translations.ugettext('Fuzzes')
4014 u'Fuzzes'
4015
4016 Parameters
4017
4018 • fileobj – the file-like object to write to
4019
4020 • catalog – the Catalog instance
4021
4022 • use_fuzzy – whether translations marked as “fuzzy”
4023 should be included in the output
4024
4025 PO File Support
4026 The PO file support can read and write PO and POT files. It reads them
4027 into Catalog objects and also writes catalogs out.
4028
4029 babel.messages.pofile.read_po(fileobj, locale=None, domain=None, ig‐
4030 nore_obsolete=False, charset=None, abort_invalid=False)
4031 Read messages from a gettext PO (portable object) file from the
4032 given file-like object and return a Catalog.
4033
4034 >>> from datetime import datetime
4035 >>> from io import StringIO
4036 >>> buf = StringIO('''
4037 ... #: main.py:1
4038 ... #, fuzzy, python-format
4039 ... msgid "foo %(name)s"
4040 ... msgstr "quux %(name)s"
4041 ...
4042 ... # A user comment
4043 ... #. An auto comment
4044 ... #: main.py:3
4045 ... msgid "bar"
4046 ... msgid_plural "baz"
4047 ... msgstr[0] "bar"
4048 ... msgstr[1] "baaz"
4049 ... ''')
4050 >>> catalog = read_po(buf)
4051 >>> catalog.revision_date = datetime(2007, 4, 1)
4052
4053 >>> for message in catalog:
4054 ... if message.id:
4055 ... print((message.id, message.string))
4056 ... print(' ', (message.locations, sorted(list(message.flags))))
4057 ... print(' ', (message.user_comments, message.auto_comments))
4058 (u'foo %(name)s', u'quux %(name)s')
4059 ([(u'main.py', 1)], [u'fuzzy', u'python-format'])
4060 ([], [])
4061 ((u'bar', u'baz'), (u'bar', u'baaz'))
4062 ([(u'main.py', 3)], [])
4063 ([u'A user comment'], [u'An auto comment'])
4064
4065 New in version 1.0: Added support for explicit charset argument.
4066
4067
4068 Parameters
4069
4070 • fileobj – the file-like object to read the PO file from
4071
4072 • locale – the locale identifier or Locale object, or
4073 None if the catalog is not bound to a locale (which ba‐
4074 sically means it’s a template)
4075
4076 • domain – the message domain
4077
4078 • ignore_obsolete – whether to ignore obsolete messages
4079 in the input
4080
4081 • charset – the character set of the catalog.
4082
4083 • abort_invalid – abort read if po file is invalid
4084
4085 babel.messages.pofile.write_po(fileobj, catalog, width=76, no_loca‐
4086 tion=False, omit_header=False, sort_output=False, sort_by_file=False,
4087 ignore_obsolete=False, include_previous=False, include_lineno=True)
4088 Write a gettext PO (portable object) template file for a given
4089 message catalog to the provided file-like object.
4090
4091 >>> catalog = Catalog()
4092 >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)],
4093 ... flags=('fuzzy',))
4094 <Message...>
4095 >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)])
4096 <Message...>
4097 >>> from io import BytesIO
4098 >>> buf = BytesIO()
4099 >>> write_po(buf, catalog, omit_header=True)
4100 >>> print(buf.getvalue().decode("utf8"))
4101 #: main.py:1
4102 #, fuzzy, python-format
4103 msgid "foo %(name)s"
4104 msgstr ""
4105
4106 #: main.py:3
4107 msgid "bar"
4108 msgid_plural "baz"
4109 msgstr[0] ""
4110 msgstr[1] ""
4111
4112
4113
4114 Parameters
4115
4116 • fileobj – the file-like object to write to
4117
4118 • catalog – the Catalog instance
4119
4120 • width – the maximum line width for the generated out‐
4121 put; use None, 0, or a negative number to completely
4122 disable line wrapping
4123
4124 • no_location – do not emit a location comment for every
4125 message
4126
4127 • omit_header – do not include the msgid "" entry at the
4128 top of the output
4129
4130 • sort_output – whether to sort the messages in the out‐
4131 put by msgid
4132
4133 • sort_by_file – whether to sort the messages in the out‐
4134 put by their locations
4135
4136 • ignore_obsolete – whether to ignore obsolete messages
4137 and not include them in the output; by default they are
4138 included as comments
4139
4140 • include_previous – include the old msgid as a comment
4141 when updating the catalog
4142
4143 • include_lineno – include line number in the location
4144 comment
4145
4146 Numbers and Currencies
4147 The number module provides functionality to format numbers for differ‐
4148 ent locales. This includes arbitrary numbers as well as currency.
4149
4150 Number Formatting
4151 babel.numbers.format_number(number, locale='en_US_POSIX')
4152 Return the given number formatted for a specific locale.
4153
4154 >>> format_number(1099, locale='en_US')
4155 u'1,099'
4156 >>> format_number(1099, locale='de_DE')
4157 u'1.099'
4158
4159 Deprecated since version 2.6.0: Use babel.numbers.format_deci‐
4160 mal() instead.
4161
4162
4163 Parameters
4164
4165 • number – the number to format
4166
4167 • locale – the Locale object or locale identifier
4168
4169 babel.numbers.format_decimal(number, format=None, locale='en_US_POSIX',
4170 decimal_quantization=True, group_separator=True)
4171 Return the given decimal number formatted for a specific locale.
4172
4173 >>> format_decimal(1.2345, locale='en_US')
4174 u'1.234'
4175 >>> format_decimal(1.2346, locale='en_US')
4176 u'1.235'
4177 >>> format_decimal(-1.2346, locale='en_US')
4178 u'-1.235'
4179 >>> format_decimal(1.2345, locale='sv_SE')
4180 u'1,234'
4181 >>> format_decimal(1.2345, locale='de')
4182 u'1,234'
4183
4184 The appropriate thousands grouping and the decimal separator are
4185 used for each locale:
4186
4187 >>> format_decimal(12345.5, locale='en_US')
4188 u'12,345.5'
4189
4190 By default the locale is allowed to truncate and round a
4191 high-precision number by forcing its format pattern onto the
4192 decimal part. You can bypass this behavior with the deci‐
4193 mal_quantization parameter:
4194
4195 >>> format_decimal(1.2346, locale='en_US')
4196 u'1.235'
4197 >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
4198 u'1.2346'
4199 >>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
4200 u'12345,67'
4201 >>> format_decimal(12345.67, locale='en_US', group_separator=True)
4202 u'12,345.67'
4203
4204 Parameters
4205
4206 • number – the number to format
4207
4208 • format –
4209
4210 • locale – the Locale object or locale identifier
4211
4212 • decimal_quantization – Truncate and round high-preci‐
4213 sion numbers to the format pattern. Defaults to True.
4214
4215 • group_separator – Boolean to switch group separator
4216 on/off in a locale’s number format.
4217
4218 babel.numbers.format_currency(number, currency, format=None, lo‐
4219 cale='en_US_POSIX', currency_digits=True, format_type='standard', deci‐
4220 mal_quantization=True, group_separator=True)
4221 Return formatted currency value.
4222
4223 >>> format_currency(1099.98, 'USD', locale='en_US')
4224 u'$1,099.98'
4225 >>> format_currency(1099.98, 'USD', locale='es_CO')
4226 u'US$\xa01.099,98'
4227 >>> format_currency(1099.98, 'EUR', locale='de_DE')
4228 u'1.099,98\xa0\u20ac'
4229
4230 The format can also be specified explicitly. The currency is
4231 placed with the ‘¤’ sign. As the sign gets repeated the format
4232 expands (¤ being the symbol, ¤¤ is the currency abbreviation and
4233 ¤¤¤ is the full name of the currency):
4234
4235 >>> format_currency(1099.98, 'EUR', u'¤¤ #,##0.00', locale='en_US')
4236 u'EUR 1,099.98'
4237 >>> format_currency(1099.98, 'EUR', u'#,##0.00 ¤¤¤', locale='en_US')
4238 u'1,099.98 euros'
4239
4240 Currencies usually have a specific number of decimal digits.
4241 This function favours that information over the given format:
4242
4243 >>> format_currency(1099.98, 'JPY', locale='en_US')
4244 u'\xa51,100'
4245 >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
4246 u'1.099,98'
4247
4248 However, the number of decimal digits can be overriden from the
4249 currency information, by setting the last parameter to False:
4250
4251 >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
4252 u'\xa51,099.98'
4253 >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
4254 u'1.099,98'
4255
4256 If a format is not specified the type of currency format to use
4257 from the locale can be specified:
4258
4259 >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
4260 u'\u20ac1,099.98'
4261
4262 When the given currency format type is not available, an excep‐
4263 tion is raised:
4264
4265 >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
4266 Traceback (most recent call last):
4267 ...
4268 UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
4269
4270 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
4271 u'$101299.98'
4272
4273 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
4274 u'$101,299.98'
4275
4276 You can also pass format_type=’name’ to use long display names.
4277 The order of the number and currency name, along with the cor‐
4278 rect localized plural form of the currency name, is chosen ac‐
4279 cording to locale:
4280
4281 >>> format_currency(1, 'USD', locale='en_US', format_type='name')
4282 u'1.00 US dollar'
4283 >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
4284 u'1,099.98 US dollars'
4285 >>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
4286 u'us ga dollar 1,099.98'
4287
4288 By default the locale is allowed to truncate and round a
4289 high-precision number by forcing its format pattern onto the
4290 decimal part. You can bypass this behavior with the deci‐
4291 mal_quantization parameter:
4292
4293 >>> format_currency(1099.9876, 'USD', locale='en_US')
4294 u'$1,099.99'
4295 >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
4296 u'$1,099.9876'
4297
4298 Parameters
4299
4300 • number – the number to format
4301
4302 • currency – the currency code
4303
4304 • format – the format string to use
4305
4306 • locale – the Locale object or locale identifier
4307
4308 • currency_digits – use the currency’s natural number of
4309 decimal digits
4310
4311 • format_type – the currency format type to use
4312
4313 • decimal_quantization – Truncate and round high-preci‐
4314 sion numbers to the format pattern. Defaults to True.
4315
4316 • group_separator – Boolean to switch group separator
4317 on/off in a locale’s number format.
4318
4319 babel.numbers.format_percent(number, format=None, locale='en_US_POSIX',
4320 decimal_quantization=True, group_separator=True)
4321 Return formatted percent value for a specific locale.
4322
4323 >>> format_percent(0.34, locale='en_US')
4324 u'34%'
4325 >>> format_percent(25.1234, locale='en_US')
4326 u'2,512%'
4327 >>> format_percent(25.1234, locale='sv_SE')
4328 u'2\xa0512\xa0%'
4329
4330 The format pattern can also be specified explicitly:
4331
4332 >>> format_percent(25.1234, u'#,##0‰', locale='en_US')
4333 u'25,123‰'
4334
4335 By default the locale is allowed to truncate and round a
4336 high-precision number by forcing its format pattern onto the
4337 decimal part. You can bypass this behavior with the deci‐
4338 mal_quantization parameter:
4339
4340 >>> format_percent(23.9876, locale='en_US')
4341 u'2,399%'
4342 >>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
4343 u'2,398.76%'
4344
4345 >>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
4346 u'22929112%'
4347
4348 >>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
4349 u'22.929.112%'
4350
4351 Parameters
4352
4353 • number – the percent number to format
4354
4355 • format –
4356
4357 • locale – the Locale object or locale identifier
4358
4359 • decimal_quantization – Truncate and round high-preci‐
4360 sion numbers to the format pattern. Defaults to True.
4361
4362 • group_separator – Boolean to switch group separator
4363 on/off in a locale’s number format.
4364
4365 babel.numbers.format_scientific(number, format=None, lo‐
4366 cale='en_US_POSIX', decimal_quantization=True)
4367 Return value formatted in scientific notation for a specific lo‐
4368 cale.
4369
4370 >>> format_scientific(10000, locale='en_US')
4371 u'1E4'
4372
4373 The format pattern can also be specified explicitly:
4374
4375 >>> format_scientific(1234567, u'##0.##E00', locale='en_US')
4376 u'1.23E06'
4377
4378 By default the locale is allowed to truncate and round a
4379 high-precision number by forcing its format pattern onto the
4380 decimal part. You can bypass this behavior with the deci‐
4381 mal_quantization parameter:
4382
4383 >>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
4384 u'1.23E3'
4385 >>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
4386 u'1.2349876E3'
4387
4388 Parameters
4389
4390 • number – the number to format
4391
4392 • format –
4393
4394 • locale – the Locale object or locale identifier
4395
4396 • decimal_quantization – Truncate and round high-preci‐
4397 sion numbers to the format pattern. Defaults to True.
4398
4399 Number Parsing
4400 babel.numbers.parse_number(string, locale='en_US_POSIX')
4401 Parse localized number string into an integer.
4402
4403 >>> parse_number('1,099', locale='en_US')
4404 1099
4405 >>> parse_number('1.099', locale='de_DE')
4406 1099
4407
4408 When the given string cannot be parsed, an exception is raised:
4409
4410 >>> parse_number('1.099,98', locale='de')
4411 Traceback (most recent call last):
4412 ...
4413 NumberFormatError: '1.099,98' is not a valid number
4414
4415 Parameters
4416
4417 • string – the string to parse
4418
4419 • locale – the Locale object or locale identifier
4420
4421 Returns
4422 the parsed number
4423
4424 Raises NumberFormatError – if the string can not be converted to
4425 a number
4426
4427 babel.numbers.parse_decimal(string, locale='en_US_POSIX', strict=False)
4428 Parse localized decimal string into a decimal.
4429
4430 >>> parse_decimal('1,099.98', locale='en_US')
4431 Decimal('1099.98')
4432 >>> parse_decimal('1.099,98', locale='de')
4433 Decimal('1099.98')
4434 >>> parse_decimal('12 345,123', locale='ru')
4435 Decimal('12345.123')
4436
4437 When the given string cannot be parsed, an exception is raised:
4438
4439 >>> parse_decimal('2,109,998', locale='de')
4440 Traceback (most recent call last):
4441 ...
4442 NumberFormatError: '2,109,998' is not a valid decimal number
4443
4444 If strict is set to True and the given string contains a number
4445 formatted in an irregular way, an exception is raised:
4446
4447 >>> parse_decimal('30.00', locale='de', strict=True)
4448 Traceback (most recent call last):
4449 ...
4450 NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
4451
4452 >>> parse_decimal('0.00', locale='de', strict=True)
4453 Traceback (most recent call last):
4454 ...
4455 NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
4456
4457 Parameters
4458
4459 • string – the string to parse
4460
4461 • locale – the Locale object or locale identifier
4462
4463 • strict – controls whether numbers formatted in a weird
4464 way are accepted or rejected
4465
4466 Raises NumberFormatError – if the string can not be converted to
4467 a decimal number
4468
4469 Exceptions
4470 exception babel.numbers.NumberFormatError(message, suggestions=None)
4471 Exception raised when a string cannot be parsed into a number.
4472
4473 suggestions
4474 a list of properly formatted numbers derived from the in‐
4475 valid input
4476
4477 Data Access
4478 babel.numbers.get_currency_name(currency, count=None, lo‐
4479 cale='en_US_POSIX')
4480 Return the name used by the locale for the specified currency.
4481
4482 >>> get_currency_name('USD', locale='en_US')
4483 u'US Dollar'
4484
4485 New in version 0.9.4.
4486
4487
4488 Parameters
4489
4490 • currency – the currency code.
4491
4492 • count – the optional count. If provided the currency
4493 name will be pluralized to that number if possible.
4494
4495 • locale – the Locale object or locale identifier.
4496
4497 babel.numbers.get_currency_symbol(currency, locale='en_US_POSIX')
4498 Return the symbol used by the locale for the specified currency.
4499
4500 >>> get_currency_symbol('USD', locale='en_US')
4501 u'$'
4502
4503 Parameters
4504
4505 • currency – the currency code.
4506
4507 • locale – the Locale object or locale identifier.
4508
4509 babel.numbers.get_currency_unit_pattern(currency, count=None, lo‐
4510 cale='en_US_POSIX')
4511 Return the unit pattern used for long display of a currency
4512 value for a given locale. This is a string containing {0} where
4513 the numeric part should be substituted and {1} where the cur‐
4514 rency long display name should be substituted.
4515
4516 >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
4517 u'{0} {1}'
4518
4519 New in version 2.7.0.
4520
4521
4522 Parameters
4523
4524 • currency – the currency code.
4525
4526 • count – the optional count. If provided the unit pat‐
4527 tern for that number will be returned.
4528
4529 • locale – the Locale object or locale identifier.
4530
4531 babel.numbers.get_decimal_symbol(locale='en_US_POSIX')
4532 Return the symbol used by the locale to separate decimal frac‐
4533 tions.
4534
4535 >>> get_decimal_symbol('en_US')
4536 u'.'
4537
4538 Parameters
4539 locale – the Locale object or locale identifier
4540
4541 babel.numbers.get_plus_sign_symbol(locale='en_US_POSIX')
4542 Return the plus sign symbol used by the current locale.
4543
4544 >>> get_plus_sign_symbol('en_US')
4545 u'+'
4546
4547 Parameters
4548 locale – the Locale object or locale identifier
4549
4550 babel.numbers.get_minus_sign_symbol(locale='en_US_POSIX')
4551 Return the plus sign symbol used by the current locale.
4552
4553 >>> get_minus_sign_symbol('en_US')
4554 u'-'
4555
4556 Parameters
4557 locale – the Locale object or locale identifier
4558
4559 babel.numbers.get_territory_currencies(territory, start_date=None,
4560 end_date=None, tender=True, non_tender=False, include_details=False)
4561 Returns the list of currencies for the given territory that are
4562 valid for the given date range. In addition to that the cur‐
4563 rency database distinguishes between tender and non-tender cur‐
4564 rencies. By default only tender currencies are returned.
4565
4566 The return value is a list of all currencies roughly ordered by
4567 the time of when the currency became active. The longer the
4568 currency is being in use the more to the left of the list it
4569 will be.
4570
4571 The start date defaults to today. If no end date is given it
4572 will be the same as the start date. Otherwise a range can be
4573 defined. For instance this can be used to find the currencies
4574 in use in Austria between 1995 and 2011:
4575
4576 >>> from datetime import date
4577 >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
4578 ['ATS', 'EUR']
4579
4580 Likewise it’s also possible to find all the currencies in use on
4581 a single date:
4582
4583 >>> get_territory_currencies('AT', date(1995, 1, 1))
4584 ['ATS']
4585 >>> get_territory_currencies('AT', date(2011, 1, 1))
4586 ['EUR']
4587
4588 By default the return value only includes tender currencies.
4589 This however can be changed:
4590
4591 >>> get_territory_currencies('US')
4592 ['USD']
4593 >>> get_territory_currencies('US', tender=False, non_tender=True,
4594 ... start_date=date(2014, 1, 1))
4595 ['USN', 'USS']
4596
4597 New in version 2.0.
4598
4599
4600 Parameters
4601
4602 • territory – the name of the territory to find the cur‐
4603 rency for.
4604
4605 • start_date – the start date. If not given today is as‐
4606 sumed.
4607
4608 • end_date – the end date. If not given the start date
4609 is assumed.
4610
4611 • tender – controls whether tender currencies should be
4612 included.
4613
4614 • non_tender – controls whether non-tender currencies
4615 should be included.
4616
4617 • include_details – if set to True, instead of returning
4618 currency codes the return value will be dictionaries
4619 with detail information. In that case each dictionary
4620 will have the keys 'currency', 'from', 'to', and 'ten‐
4621 der'.
4622
4623 Pluralization Support
4624 The pluralization support provides functionality around the CLDR plu‐
4625 ralization rules. It can parse and evaluate pluralization rules, as
4626 well as convert them to other formats such as gettext.
4627
4628 Basic Interface
4629 class babel.plural.PluralRule(rules)
4630 Represents a set of language pluralization rules. The construc‐
4631 tor accepts a list of (tag, expr) tuples or a dict of CLDR
4632 rules. The resulting object is callable and accepts one parame‐
4633 ter with a positive or negative number (both integer and float)
4634 for the number that indicates the plural form for a string and
4635 returns the tag for the format:
4636
4637 >>> rule = PluralRule({'one': 'n is 1'})
4638 >>> rule(1)
4639 'one'
4640 >>> rule(2)
4641 'other'
4642
4643 Currently the CLDR defines these tags: zero, one, two, few, many
4644 and other where other is an implicit default. Rules should be
4645 mutually exclusive; for a given numeric value, only one rule
4646 should apply (i.e. the condition should only be true for one of
4647 the plural rule elements.
4648
4649 classmethod parse(rules)
4650 Create a PluralRule instance for the given rules. If the
4651 rules are a PluralRule object, that object is returned.
4652
4653 Parameters
4654 rules – the rules as list or dict, or a PluralRule
4655 object
4656
4657 Raises RuleError – if the expression is malformed
4658
4659 property rules
4660 The PluralRule as a dict of unicode plural rules.
4661
4662 >>> rule = PluralRule({'one': 'n is 1'})
4663 >>> rule.rules
4664 {'one': 'n is 1'}
4665
4666 property tags
4667 A set of explicitly defined tags in this rule. The im‐
4668 plicit default 'other' rules is not part of this set un‐
4669 less there is an explicit rule for it.
4670
4671 Conversion Functionality
4672 babel.plural.to_javascript(rule)
4673 Convert a list/dict of rules or a PluralRule object into a Java‐
4674 Script function. This function depends on no external library:
4675
4676 >>> to_javascript({'one': 'n is 1'})
4677 "(function(n) { return (n == 1) ? 'one' : 'other'; })"
4678
4679 Implementation detail: The function generated will probably
4680 evaluate expressions involved into range operations multiple
4681 times. This has the advantage that external helper functions
4682 are not required and is not a big performance hit for these sim‐
4683 ple calculations.
4684
4685 Parameters
4686 rule – the rules as list or dict, or a PluralRule object
4687
4688 Raises RuleError – if the expression is malformed
4689
4690 babel.plural.to_python(rule)
4691 Convert a list/dict of rules or a PluralRule object into a regu‐
4692 lar Python function. This is useful in situations where you
4693 need a real function and don’t are about the actual rule object:
4694
4695 >>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
4696 >>> func(1)
4697 'one'
4698 >>> func(3)
4699 'few'
4700 >>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
4701 >>> func(11)
4702 'one'
4703 >>> func(15)
4704 'few'
4705
4706 Parameters
4707 rule – the rules as list or dict, or a PluralRule object
4708
4709 Raises RuleError – if the expression is malformed
4710
4711 babel.plural.to_gettext(rule)
4712 The plural rule as gettext expression. The gettext expression
4713 is technically limited to integers and returns indices rather
4714 than tags.
4715
4716 >>> to_gettext({'one': 'n is 1', 'two': 'n is 2'})
4717 'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2);'
4718
4719 Parameters
4720 rule – the rules as list or dict, or a PluralRule object
4721
4722 Raises RuleError – if the expression is malformed
4723
4724 General Support Functionality
4725 Babel ships a few general helpers that are not being used by Babel it‐
4726 self but are useful in combination with functionality provided by it.
4727
4728 Convenience Helpers
4729 class babel.support.Format(locale, tzinfo=None)
4730 Wrapper class providing the various date and number formatting
4731 functions bound to a specific locale and time-zone.
4732
4733 >>> from babel.util import UTC
4734 >>> from datetime import date
4735 >>> fmt = Format('en_US', UTC)
4736 >>> fmt.date(date(2007, 4, 1))
4737 u'Apr 1, 2007'
4738 >>> fmt.decimal(1.2345)
4739 u'1.234'
4740
4741 currency(number, currency)
4742 Return a number in the given currency formatted for the
4743 locale.
4744
4745 date(date=None, format='medium')
4746 Return a date formatted according to the given pattern.
4747
4748 >>> from datetime import date
4749 >>> fmt = Format('en_US')
4750 >>> fmt.date(date(2007, 4, 1))
4751 u'Apr 1, 2007'
4752
4753 datetime(datetime=None, format='medium')
4754 Return a date and time formatted according to the given
4755 pattern.
4756
4757 >>> from datetime import datetime
4758 >>> from pytz import timezone
4759 >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
4760 >>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
4761 u'Apr 1, 2007, 11:30:00 AM'
4762
4763 decimal(number, format=None)
4764 Return a decimal number formatted for the locale.
4765
4766 >>> fmt = Format('en_US')
4767 >>> fmt.decimal(1.2345)
4768 u'1.234'
4769
4770 number(number)
4771 Return an integer number formatted for the locale.
4772
4773 >>> fmt = Format('en_US')
4774 >>> fmt.number(1099)
4775 u'1,099'
4776
4777 percent(number, format=None)
4778 Return a number formatted as percentage for the locale.
4779
4780 >>> fmt = Format('en_US')
4781 >>> fmt.percent(0.34)
4782 u'34%'
4783
4784 scientific(number)
4785 Return a number formatted using scientific notation for
4786 the locale.
4787
4788 time(time=None, format='medium')
4789 Return a time formatted according to the given pattern.
4790
4791 >>> from datetime import datetime
4792 >>> from pytz import timezone
4793 >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
4794 >>> fmt.time(datetime(2007, 4, 1, 15, 30))
4795 u'11:30:00 AM'
4796
4797 timedelta(delta, granularity='second', threshold=0.85, for‐
4798 mat='long', add_direction=False)
4799 Return a time delta according to the rules of the given
4800 locale.
4801
4802 >>> from datetime import timedelta
4803 >>> fmt = Format('en_US')
4804 >>> fmt.timedelta(timedelta(weeks=11))
4805 u'3 months'
4806
4807 class babel.support.LazyProxy(func, *args, **kwargs)
4808 Class for proxy objects that delegate to a specified function to
4809 evaluate the actual object.
4810
4811 >>> def greeting(name='world'):
4812 ... return 'Hello, %s!' % name
4813 >>> lazy_greeting = LazyProxy(greeting, name='Joe')
4814 >>> print(lazy_greeting)
4815 Hello, Joe!
4816 >>> u' ' + lazy_greeting
4817 u' Hello, Joe!'
4818 >>> u'(%s)' % lazy_greeting
4819 u'(Hello, Joe!)'
4820
4821 This can be used, for example, to implement lazy translation
4822 functions that delay the actual translation until the string is
4823 actually used. The rationale for such behavior is that the lo‐
4824 cale of the user may not always be available. In web applica‐
4825 tions, you only know the locale when processing a request.
4826
4827 The proxy implementation attempts to be as complete as possible,
4828 so that the lazy objects should mostly work as expected, for ex‐
4829 ample for sorting:
4830
4831 >>> greetings = [
4832 ... LazyProxy(greeting, 'world'),
4833 ... LazyProxy(greeting, 'Joe'),
4834 ... LazyProxy(greeting, 'universe'),
4835 ... ]
4836 >>> greetings.sort()
4837 >>> for greeting in greetings:
4838 ... print(greeting)
4839 Hello, Joe!
4840 Hello, universe!
4841 Hello, world!
4842
4843 Gettext Support
4844 class babel.support.Translations(fp=None, domain=None)
4845 An extended translation catalog class.
4846
4847 add(translations, merge=True)
4848 Add the given translations to the catalog.
4849
4850 If the domain of the translations is different than that
4851 of the current catalog, they are added as a catalog that
4852 is only accessible by the various d*gettext functions.
4853
4854 Parameters
4855
4856 • translations – the Translations instance with
4857 the messages to add
4858
4859 • merge – whether translations for message domains
4860 that have already been added should be merged
4861 with the existing translations
4862
4863 classmethod load(dirname=None, locales=None, domain=None)
4864 Load translations from the given directory.
4865
4866 Parameters
4867
4868 • dirname – the directory containing the MO files
4869
4870 • locales – the list of locales in order of pref‐
4871 erence (items in this list can be either Locale
4872 objects or locale strings)
4873
4874 • domain – the message domain (default: ‘mes‐
4875 sages’)
4876
4877 merge(translations)
4878 Merge the given translations into the catalog.
4879
4880 Message translations in the specified catalog override
4881 any messages with the same identifier in the existing
4882 catalog.
4883
4884 Parameters
4885 translations – the Translations instance with the
4886 messages to merge
4887
4888 Units
4889 The unit module provides functionality to format measurement units for
4890 different locales.
4891
4892 babel.units.format_unit(value, measurement_unit, length='long', for‐
4893 mat=None, locale='en_US_POSIX')
4894 Format a value of a given unit.
4895
4896 Values are formatted according to the locale’s usual pluraliza‐
4897 tion rules and number formats.
4898
4899 >>> format_unit(12, 'length-meter', locale='ro_RO')
4900 u'12 metri'
4901 >>> format_unit(15.5, 'length-mile', locale='fi_FI')
4902 u'15,5 mailia'
4903 >>> format_unit(1200, 'pressure-millimeter-ofhg', locale='nb')
4904 u'1\xa0200 millimeter kvikks\xf8lv'
4905 >>> format_unit(270, 'ton', locale='en')
4906 u'270 tons'
4907
4908 Number formats may be overridden with the format parameter.
4909
4910 >>> import decimal
4911 >>> format_unit(decimal.Decimal("-42.774"), 'temperature-celsius', 'short', format='#.0', locale='fr')
4912 u'-42,8\u202f\xb0C'
4913
4914 The locale’s usual pluralization rules are respected.
4915
4916 >>> format_unit(1, 'length-meter', locale='ro_RO')
4917 u'1 metru'
4918 >>> format_unit(0, 'length-mile', locale='cy')
4919 u'0 mi'
4920 >>> format_unit(1, 'length-mile', locale='cy')
4921 u'1 filltir'
4922 >>> format_unit(3, 'length-mile', locale='cy')
4923 u'3 milltir'
4924
4925 >>> format_unit(15, 'length-horse', locale='fi')
4926 Traceback (most recent call last):
4927 ...
4928 UnknownUnitError: length-horse is not a known unit in fi
4929
4930 New in version 2.2.0.
4931
4932
4933 Parameters
4934
4935 • value – the value to format. If this is a string, no
4936 number formatting will be attempted.
4937
4938 • measurement_unit – the code of a measurement unit.
4939 Known units can be found in the CLDR Unit Validity XML
4940 file:
4941 https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
4942
4943 • length – “short”, “long” or “narrow”
4944
4945 • format – An optional format, as accepted by format_dec‐
4946 imal.
4947
4948 • locale – the Locale object or locale identifier
4949
4950 babel.units.format_compound_unit(numerator_value, numerator_unit=None,
4951 denominator_value=1, denominator_unit=None, length='long', format=None,
4952 locale='en_US_POSIX')
4953 Format a compound number value, i.e. “kilometers per hour” or
4954 similar.
4955
4956 Both unit specifiers are optional to allow for formatting of ar‐
4957 bitrary values still according to the locale’s general “per”
4958 formatting specifier.
4959
4960 >>> format_compound_unit(7, denominator_value=11, length="short", locale="pt")
4961 '7/11'
4962
4963 >>> format_compound_unit(150, "kilometer", denominator_unit="hour", locale="sv")
4964 '150 kilometer per timme'
4965
4966 >>> format_compound_unit(150, "kilowatt", denominator_unit="year", locale="fi")
4967 '150 kilowattia / vuosi'
4968
4969 >>> format_compound_unit(32.5, "ton", 15, denominator_unit="hour", locale="en")
4970 '32.5 tons per 15 hours'
4971
4972 >>> format_compound_unit(160, denominator_unit="square-meter", locale="fr")
4973 '160 par m\xe8tre carr\xe9'
4974
4975 >>> format_compound_unit(4, "meter", "ratakisko", length="short", locale="fi")
4976 '4 m/ratakisko'
4977
4978 >>> format_compound_unit(35, "minute", denominator_unit="fathom", locale="sv")
4979 '35 minuter per famn'
4980
4981 >>> from babel.numbers import format_currency
4982 >>> format_compound_unit(format_currency(35, "JPY", locale="de"), denominator_unit="liter", locale="de")
4983 '35\xa0\xa5 pro Liter'
4984
4985 See
4986 https://www.unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
4987
4988 Parameters
4989
4990 • numerator_value – The numerator value. This may be a
4991 string, in which case it is considered preformatted and
4992 the unit is ignored.
4993
4994 • numerator_unit – The numerator unit. See format_unit.
4995
4996 • denominator_value – The denominator value. This may be
4997 a string, in which case it is considered preformatted
4998 and the unit is ignored.
4999
5000 • denominator_unit – The denominator unit. See for‐
5001 mat_unit.
5002
5003 • length – The formatting length. “short”, “long” or
5004 “narrow”
5005
5006 • format – An optional format, as accepted by format_dec‐
5007 imal.
5008
5009 • locale – the Locale object or locale identifier
5010
5011 Returns
5012 A formatted compound value.
5013
5014 babel.units.get_unit_name(measurement_unit, length='long', lo‐
5015 cale='en_US_POSIX')
5016 Get the display name for a measurement unit in the given locale.
5017
5018 >>> get_unit_name("radian", locale="en")
5019 'radians'
5020
5021 Unknown units will raise exceptions:
5022
5023 >>> get_unit_name("battery", locale="fi")
5024 Traceback (most recent call last):
5025 ...
5026 UnknownUnitError: battery/long is not a known unit/length in fi
5027
5028 Parameters
5029
5030 • measurement_unit – the code of a measurement unit.
5031 Known units can be found in the CLDR Unit Validity XML
5032 file:
5033 https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
5034
5035 • length – “short”, “long” or “narrow”
5036
5037 • locale – the Locale object or locale identifier
5038
5039 Returns
5040 The unit display name, or None.
5041
5043 Babel Development
5044 Babel as a library has a long history that goes back to the Trac
5045 project. Since then it has evolved into an independently developed
5046 project that implements data access for the CLDR project.
5047
5048 This document tries to explain as best as possible the general rules of
5049 the project in case you want to help out developing.
5050
5051 Tracking the CLDR
5052 Generally the goal of the project is to work as closely as possible
5053 with the CLDR data. This has in the past caused some frustrating prob‐
5054 lems because the data is entirely out of our hand. To minimize the
5055 frustration we generally deal with CLDR updates the following way:
5056
5057 • bump the CLDR data only with a major release of Babel.
5058
5059 • never perform custom bugfixes on the CLDR data.
5060
5061 • never work around CLDR bugs within Babel. If you find a problem in
5062 the data, report it upstream.
5063
5064 • adjust the parsing of the data as soon as possible, otherwise this
5065 will spiral out of control later. This is especially the case for
5066 bigger updates that change pluralization and more.
5067
5068 • try not to test against specific CLDR data that is likely to change.
5069
5070 Python Versions
5071 At the moment the following Python versions should be supported:
5072
5073 • Python 2.7
5074
5075 • Python 3.4 and up
5076
5077 • PyPy tracking 2.7 and 3.2 and up
5078
5079 While PyPy does not currently support 3.3, it does support traditional
5080 unicode literals which simplifies the entire situation tremendously.
5081
5082 Documentation must build on Python 2, Python 3 support for the documen‐
5083 tation is an optional goal. Code examples in the docs preferably are
5084 written in a style that makes them work on both 2.x and 3.x with pref‐
5085 erence to the former.
5086
5087 Unicode
5088 Unicode is a big deal in Babel. Here is how the rules are set up:
5089
5090 • internally everything is unicode that makes sense to have as unicode.
5091 The exception to this rule are things which on Python 2 traditionally
5092 have been bytes. For example file names on Python 2 should be
5093 treated as bytes wherever possible.
5094
5095 • Encode / decode at boundaries explicitly. Never assume an encoding
5096 in a way it cannot be overridden. utf-8 should be generally consid‐
5097 ered the default encoding.
5098
5099 • Dot not use unicode_literals, instead use the u'' string syntax. The
5100 reason for this is that the former introduces countless of unicode
5101 problems by accidentally upgrading strings to unicode which should
5102 not be. (docstrings for instance).
5103
5104 Dates and Timezones
5105 Generally all timezone support in Babel is based on pytz which it just
5106 depends on. Babel should assume that timezone objects are pytz based
5107 because those are the only ones with an API that actually work cor‐
5108 rectly (due to the API problems with non UTC based timezones).
5109
5110 Assumptions to make:
5111
5112 • use UTC where possible.
5113
5114 • be super careful with local time. Do not use local time without
5115 knowing the exact timezone.
5116
5117 • time without date is a very useless construct. Do not try to support
5118 timezones for it. If you do, assume that the current local date is
5119 assumed and not utc date.
5120
5121 Babel Changelog
5122 Version 2.10.3
5123 This is a bugfix release for Babel 2.10.2, which was mistakenly pack‐
5124 aged with outdated locale data.
5125
5126 Thanks to Michał Górny for pointing this out and Jun Omae for verify‐
5127 ing.
5128
5129 This and future Babel PyPI packages will be built by a more automated
5130 process, which should make problems like this less likely to occur.
5131
5132 Version 2.10.2
5133 This is a bugfix release for Babel 2.10.1.
5134
5135 • Fallback count=”other” format in format_currency() (#872) - Jun Omae
5136
5137 • Fix get_period_id() with dayPeriodRule across 0:00 (#871) - Jun Omae
5138
5139 • Add support for b and B period symbols in time format (#869) - Jun
5140 Omae
5141
5142 • chore(docs/typo): Fixes a minor typo in a function comment (#864) -
5143 Frank Harrison
5144
5145 Version 2.10.1
5146 This is a bugfix release for Babel 2.10.0.
5147
5148 • Messages: Fix distutils import. Regressed in #843. (#852) - Nehal J
5149 Wani
5150
5151 • The wheel file is no longer marked as universal, since Babel only
5152 supports Python 3.
5153
5154 Version 2.10.0
5155 Upcoming deprecation
5156 • The get_next_timezone_transition() function is marked deprecated in
5157 this version and will be removed likely as soon as Babel 2.11. No
5158 replacement for this function is planned; based on discussion in
5159 #716, it’s likely the function is not used in any real code. (#852) -
5160 Aarni Koskela, Paul Ganssle
5161
5162 Improvements
5163 • CLDR: Upgrade to CLDR 41.0. (#853) - Aarni Koskela
5164
5165 • The c and e plural form operands introduced in CLDR 40 are
5166 parsed, but otherwise unsupported. (#826)
5167
5168 • Non-nominative forms of units are currently ignored.
5169
5170 • Messages: Implement --init-missing option for pybabel update (#785) -
5171 ruro
5172
5173 • Messages: For extract, you can now replace the built-in .* / _* ig‐
5174 nored directory patterns with ones of your own. (#832) - Aarni
5175 Koskela, Kinshuk Dua
5176
5177 • Messages: Add --check to verify if catalogs are up-to-date (#831) -
5178 Krzysztof Jagiełło
5179
5180 • Messages: Add --header-comment to override default header comment (‐
5181 #720) - Mohamed Hafez Morsy, Aarni Koskela
5182
5183 • Dates: parse_time now supports 12-hour clock, and is better at pars‐
5184 ing partial times. (#834) - Aarni Koskela, David Bauer, Arthur Jo‐
5185 vart
5186
5187 • Dates: parse_date and parse_time now raise ParseError, a subclass of
5188 ValueError, in certain cases. (#834) - Aarni Koskela
5189
5190 • Dates: parse_date and parse_time now accept the format parameter. (‐
5191 #834) - Juliette Monsel, Aarni Koskela
5192
5193 Infrastructure
5194 • The internal babel/_compat.py module is no more (#808) - Hugo van Ke‐
5195 menade
5196
5197 • Python 3.10 is officially supported (#809) - Hugo van Kemenade
5198
5199 • There’s now a friendly GitHub issue template. (#800) – Álvaro
5200 Mondéjar Rubio
5201
5202 • Don’t use the deprecated format_number function internally or in
5203 tests - Aarni Koskela
5204
5205 • Add GitHub URL for PyPi (#846) - Andrii Oriekhov
5206
5207 • Python 3.12 compatibility: Prefer setuptools imports to distutils im‐
5208 ports (#843) - Aarni Koskela
5209
5210 • Python 3.11 compatibility: Add deprecations to l*gettext variants (‐
5211 #835) - Aarni Koskela
5212
5213 • CI: Babel is now tested with PyPy 3.7. (#851) - Aarni Koskela
5214
5215 Bugfixes
5216 • Date formatting: Allow using other as fallback form (#827) - Aarni
5217 Koskela
5218
5219 • Locales: Locale.parse() normalizes variant tags to upper case (#829)
5220 - Aarni Koskela
5221
5222 • A typo in the plural format for Maltese is fixed. (#796) - Lukas Win‐
5223 kler
5224
5225 • Messages: Catalog date parsing is now timezone independent. (#701) -
5226 rachele-collin
5227
5228 • Messages: Fix duplicate locations when writing without lineno (#837)
5229 - Sigurd Ljødal
5230
5231 • Messages: Fix missing trailing semicolon in plural form headers (‐
5232 #848) - farhan5900
5233
5234 • CLI: Fix output of --list-locales to not be a bytes repr (#845) -
5235 Morgan Wahl
5236
5237 Documentation
5238 • Documentation is now correctly built again, and up to date (#830) -
5239 Aarni Koskela
5240
5241 Version 2.9.1
5242 Bugfixes
5243 • The internal locale-data loading functions now validate the name of
5244 the locale file to be loaded and only allow files within Babel’s data
5245 directory. Thank you to Chris Lyne of Tenable, Inc. for discovering
5246 the issue!
5247
5248 Version 2.9.0
5249 Upcoming version support changes
5250 • This version, Babel 2.9, is the last version of Babel to support
5251 Python 2.7, Python 3.4, and Python 3.5.
5252
5253 Improvements
5254 • CLDR: Use CLDR 37 – Aarni Koskela (#734)
5255
5256 • Dates: Handle ZoneInfo objects in get_timezone_location, get_time‐
5257 zone_name - Alessio Bogon (#741)
5258
5259 • Numbers: Add group_separator feature in number formatting - Abdullah
5260 Javed Nesar (#726)
5261
5262 Bugfixes
5263 • Dates: Correct default Format().timedelta format to ‘long’ to mute
5264 deprecation warnings – Aarni Koskela
5265
5266 • Import: Simplify iteration code in “import_cldr.py” – Felix Schwarz
5267
5268 • Import: Stop using deprecated ElementTree methods “getchildren()” and
5269 “getiterator()” – Felix Schwarz
5270
5271 • Messages: Fix unicode printing error on Python 2 without TTY. –
5272 Niklas Hambüchen
5273
5274 • Messages: Introduce invariant that _invalid_pofile() takes unicode
5275 line. – Niklas Hambüchen
5276
5277 • Tests: fix tests when using Python 3.9 – Felix Schwarz
5278
5279 • Tests: Remove deprecated ‘sudo: false’ from Travis configuration –
5280 Jon Dufresne
5281
5282 • Tests: Support Py.test 6.x – Aarni Koskela
5283
5284 • Utilities: LazyProxy: Handle AttributeError in specified func – Niki‐
5285 forov Konstantin (#724)
5286
5287 • Utilities: Replace usage of parser.suite with ast.parse – Miro
5288 Hrončok
5289
5290 Documentation
5291 • Update parse_number comments – Brad Martin (#708)
5292
5293 • Add __iter__ to Catalog documentation – @CyanNani123
5294
5295 Version 2.8.1
5296 This is solely a patch release to make running tests on Py.test 6+ pos‐
5297 sible.
5298
5299 Bugfixes
5300 • Support Py.test 6 - Aarni Koskela (#747, #750, #752)
5301
5302 Version 2.8.0
5303 Improvements
5304 • CLDR: Upgrade to CLDR 36.0 - Aarni Koskela (#679)
5305
5306 • Messages: Don’t even open files with the “ignore” extraction method -
5307 @sebleblanc (#678)
5308
5309 Bugfixes
5310 • Numbers: Fix formatting very small decimals when quantization is dis‐
5311 abled - Lev Lybin, @miluChen (#662)
5312
5313 • Messages: Attempt to sort all messages – Mario Frasca (#651, #606)
5314
5315 Docs
5316 • Add years to changelog - Romuald Brunet
5317
5318 • Note that installation requires pytz - Steve (Gadget) Barnes
5319
5320 Version 2.7.0
5321 Possibly incompatible changes
5322 These may be backward incompatible in some cases, as some more-or-less
5323 internal APIs have changed. Please feel free to file issues if you bump
5324 into anything strange and we’ll try to help!
5325
5326 • General: Internal uses of babel.util.odict have been replaced with
5327 collections.OrderedDict from The Python standard library.
5328
5329 Improvements
5330 • CLDR: Upgrade to CLDR 35.1 - Alberto Mardegan, Aarni Koskela (#626,
5331 #643)
5332
5333 • General: allow anchoring path patterns to the start of a string -
5334 Brian Cappello (#600)
5335
5336 • General: Bumped version requirement on pytz - @chrisbrake (#592)
5337
5338 • Messages: pybabel compile: exit with code 1 if errors were encoun‐
5339 tered - Aarni Koskela (#647)
5340
5341 • Messages: Add omit-header to update_catalog - Cédric Krier (#633)
5342
5343 • Messages: Catalog update: keep user comments from destination by de‐
5344 fault - Aarni Koskela (#648)
5345
5346 • Messages: Skip empty message when writing mo file - Cédric Krier (‐
5347 #564)
5348
5349 • Messages: Small fixes to avoid crashes on badly formatted .po files -
5350 Bryn Truscott (#597)
5351
5352 • Numbers: parse_decimal() strict argument and suggestions - Charly C
5353 (#590)
5354
5355 • Numbers: don’t repeat suggestions in parse_decimal strict - Serban
5356 Constantin (#599)
5357
5358 • Numbers: implement currency formatting with long display names - Luke
5359 Plant (#585)
5360
5361 • Numbers: parse_decimal(): assume spaces are equivalent to non-break‐
5362 ing spaces when not in strict mode - Aarni Koskela (#649)
5363
5364 • Performance: Cache locale_identifiers() - Aarni Koskela (#644)
5365
5366 Bugfixes
5367 • CLDR: Skip alt=… for week data (minDays, firstDay, weekendStart,
5368 weekendEnd) - Aarni Koskela (#634)
5369
5370 • Dates: Fix wrong weeknumber for 31.12.2018 - BT-sschmid (#621)
5371
5372 • Locale: Avoid KeyError trying to get data on WindowsXP - mondeja (‐
5373 #604)
5374
5375 • Locale: get_display_name(): Don’t attempt to concatenate variant in‐
5376 formation to None - Aarni Koskela (#645)
5377
5378 • Messages: pofile: Add comparison operators to _NormalizedString -
5379 Aarni Koskela (#646)
5380
5381 • Messages: pofile: don’t crash when message.locations can’t be sorted
5382 - Aarni Koskela (#646)
5383
5384 Tooling & docs
5385 • Docs: Remove all references to deprecated easy_install - Jon Dufresne
5386 (#610)
5387
5388 • Docs: Switch print statement in docs to print function - NotAFile
5389
5390 • Docs: Update all pypi.python.org URLs to pypi.org - Jon Dufresne (‐
5391 #587)
5392
5393 • Docs: Use https URLs throughout project where available - Jon
5394 Dufresne (#588)
5395
5396 • Support: Add testing and document support for Python 3.7 - Jon
5397 Dufresne (#611)
5398
5399 • Support: Test on Python 3.8-dev - Aarni Koskela (#642)
5400
5401 • Support: Using ABCs from collections instead of collections.abc is
5402 deprecated. - Julien Palard (#609)
5403
5404 • Tests: Fix conftest.py compatibility with pytest 4.3 - Miro Hrončok
5405 (#635)
5406
5407 • Tests: Update pytest and pytest-cov - Miro Hrončok (#635)
5408
5409 Version 2.6.0
5410 Possibly incompatible changes
5411 These may be backward incompatible in some cases, as some more-or-less
5412 internal APIs have changed. Please feel free to file issues if you
5413 bump into anything strange and we’ll try to help!
5414
5415 • Numbers: Refactor decimal handling code and allow bypass of decimal
5416 quantization. (@kdeldycke) (PR #538)
5417
5418 • Messages: allow processing files that are in locales unknown to Babel
5419 (@akx) (PR #557)
5420
5421 • General: Drop support for EOL Python 2.6 and 3.3 (@hugovk) (PR #546)
5422
5423 Other changes
5424 • CLDR: Use CLDR 33 (@akx) (PR #581)
5425
5426 • Lists: Add support for various list styles other than the default
5427 (@akx) (#552)
5428
5429 • Messages: Add new PoFileError exception (@Bedrock02) (PR #532)
5430
5431 • Times: Simplify Linux distro specific explicit timezone setting
5432 search (@scop) (PR #528)
5433
5434 Bugfixes
5435 • CLDR: avoid importing alt=narrow currency symbols (@akx) (PR #558)
5436
5437 • CLDR: ignore non-Latin numbering systems (@akx) (PR #579)
5438
5439 • Docs: Fix improper example for date formatting (@PTrottier) (PR #574)
5440
5441 • Tooling: Fix some deprecation warnings (@akx) (PR #580)
5442
5443 Tooling & docs
5444 • Add explicit signatures to some date autofunctions (@xmo-odoo) (PR
5445 #554)
5446
5447 • Include license file in the generated wheel package (@jdufresne) (PR
5448 #539)
5449
5450 • Python 3.6 invalid escape sequence deprecation fixes (@scop) (PR
5451 #528)
5452
5453 • Test and document all supported Python versions (@jdufresne) (PR
5454 #540)
5455
5456 • Update copyright header years and authors file (@akx) (PR #559)
5457
5458 Version 2.5.3
5459 This is a maintenance release that reverts undesired API-breaking
5460 changes that slipped into 2.5.2 (see #550).
5461
5462 It is based on v2.5.1 (f29eccd) with commits 7cedb84, 29da2d2 and
5463 edfb518 cherry-picked on top.
5464
5465 Version 2.5.2
5466 Bugfixes
5467 • Revert the unnecessary PyInstaller fixes from 2.5.0 and 2.5.1 (#533)
5468 (@yagebu)
5469
5470 Version 2.5.1
5471 Minor Improvements and bugfixes
5472 • Use a fixed datetime to avoid test failures (#520) (@narendravardi)
5473
5474 • Parse multi-line __future__ imports better (#519) (@akx)
5475
5476 • Fix validate_currency docstring (#522)
5477
5478 • Allow normalize_locale and exists to handle various unexpected inputs
5479 (#523) (@suhojm)
5480
5481 • Make PyInstaller support more robust (#525, #526) (@thijstriemstra,
5482 @akx)
5483
5484 Version 2.5.0
5485 New Features
5486 • Numbers: Add currency utilities and helpers (#491) (@kdeldycke)
5487
5488 • Support PyInstaller (#500, #505) (@wodo)
5489
5490 Minor Improvements and bugfixes
5491 • Dates: Add __str__ to DateTimePattern (#515) (@sfermigier)
5492
5493 • Dates: Fix an invalid string to bytes comparison when parsing TZ
5494 files on Py3 (#498) (@rowillia)
5495
5496 • Dates: Formatting zero-padded components of dates is faster (#517)
5497 (@akx)
5498
5499 • Documentation: Fix “Good Commits” link in CONTRIBUTING.md (#511)
5500 (@naryanacharya6)
5501
5502 • Documentation: Fix link to Python gettext module (#512) (@Linkid)
5503
5504 • Messages: Allow both dash and underscore separated locale identifiers
5505 in pofiles (#489, #490) (@akx)
5506
5507 • Messages: Extract Python messages in nested gettext calls (#488)
5508 (@sublee)
5509
5510 • Messages: Fix in-place editing of dir list while iterating (#476,
5511 #492) (@MarcDufresne)
5512
5513 • Messages: Stabilize sort order (#482) (@xavfernandez)
5514
5515 • Time zones: Honor the no-inherit marker for metazone names (#405)
5516 (@akx)
5517
5518 Version 2.4.0
5519 New Features
5520 Some of these changes might break your current code and/or tests.
5521
5522 • CLDR: CLDR 29 is now used instead of CLDR 28 (#405) (@akx)
5523
5524 • Messages: Add option ‘add_location’ for location line formatting (‐
5525 #438, #459) (@rrader, @alxpy)
5526
5527 • Numbers: Allow full control of decimal behavior (#410) (@etanol)
5528
5529 Minor Improvements and bugfixes
5530 • Documentation: Improve Date Fields descriptions (#450) (@ldwoolley)
5531
5532 • Documentation: Typo fixes and documentation improvements (#406, #412,
5533 #403, #440, #449, #463) (@zyegfryed, @adamchainz, @jwilk, @akx, @ro‐
5534 ramirez, @abhishekcs10)
5535
5536 • Messages: Default to UTF-8 source encoding instead of ISO-8859-1 (‐
5537 #399) (@asottile)
5538
5539 • Messages: Ensure messages are extracted in the order they were passed
5540 in (#424) (@ngrilly)
5541
5542 • Messages: Message extraction for JSX files is improved (#392, #396,
5543 #425) (@karloskar, @georgschoelly)
5544
5545 • Messages: PO file reading supports multi-line obsolete units (#429)
5546 (@mbirtwell)
5547
5548 • Messages: Python message extractor respects unicode_literals in __fu‐
5549 ture__ (#427) (@sublee)
5550
5551 • Messages: Roundtrip Language headers (#420) (@kruton)
5552
5553 • Messages: units before obsolete units are no longer erroneously
5554 marked obsolete (#452) (@mbirtwell)
5555
5556 • Numbers: parse_pattern now preserves the full original pattern (#414)
5557 (@jtwang)
5558
5559 • Numbers: Fix float conversion in extract_operands (#435) (@akx)
5560
5561 • Plurals: Fix plural forms for Czech and Slovak locales (#373) (@yk‐
5562 shatroff)
5563
5564 • Plurals: More plural form fixes based on Mozilla and CLDR references
5565 (#431) (@mshenfield)
5566
5567 Internal improvements
5568 • Local times are constructed correctly in tests (#411) (@etanol)
5569
5570 • Miscellaneous small improvements (#437) (@scop)
5571
5572 • Regex flags are extracted from the regex strings (#462) (@singing‐
5573 wolfboy)
5574
5575 • The PO file reader is now a class and has seen some refactoring (‐
5576 #429, #452) (@mbirtwell)
5577
5578 Version 2.3.4
5579 (Bugfix release, released on April 22th 2016)
5580
5581 Bugfixes
5582 • CLDR: The lxml library is no longer used for CLDR importing, so it
5583 should not cause strange failures either. Thanks to @aronbierbaum for
5584 the bug report and @jtwang for the fix. (‐
5585 https://github.com/python-babel/babel/pull/393)
5586
5587 • CLI: Every last single CLI usage regression should now be gone, and
5588 both distutils and stand-alone CLIs should work as they have in the
5589 past. Thanks to @paxswill and @ajaeger for bug reports. (‐
5590 https://github.com/python-babel/babel/pull/389)
5591
5592 Version 2.3.3
5593 (Bugfix release, released on April 12th 2016)
5594
5595 Bugfixes
5596 • CLI: Usage regressions that had snuck in between 2.2 and 2.3 should
5597 be no more. (https://github.com/python-babel/babel/pull/386) Thanks
5598 to @ajaeger, @sebdiem and @jcristovao for bug reports and patches.
5599
5600 Version 2.3.2
5601 (Bugfix release, released on April 9th 2016)
5602
5603 Bugfixes
5604 • Dates: Period (am/pm) formatting was broken in certain locales
5605 (namely zh_TW). Thanks to @jun66j5 for the bug report. (#378, #379)
5606
5607 Version 2.3.1
5608 (Bugfix release because of deployment problems, released on April 8th
5609 2016)
5610
5611 Version 2.3
5612 (Feature release, released on April 8th 2016)
5613
5614 Internal improvements
5615 • The CLI frontend and Distutils commands use a shared implementation
5616 (https://github.com/python-babel/babel/pull/311)
5617
5618 • PyPy3 is supported (https://github.com/python-babel/babel/pull/343)
5619
5620 Features
5621 • CLDR: Add an API for territory language data (‐
5622 https://github.com/python-babel/babel/pull/315)
5623
5624 • Core: Character order and measurement system data is imported and ex‐
5625 posed (https://github.com/python-babel/babel/pull/368)
5626
5627 • Dates: Add an API for time interval formatting (‐
5628 https://github.com/python-babel/babel/pull/316)
5629
5630 • Dates: More pattern formats and lengths are supported (‐
5631 https://github.com/python-babel/babel/pull/347)
5632
5633 • Dates: Period IDs are imported and exposed (‐
5634 https://github.com/python-babel/babel/pull/349)
5635
5636 • Dates: Support for date-time skeleton formats has been added (‐
5637 https://github.com/python-babel/babel/pull/265)
5638
5639 • Dates: Timezone formatting has been improved (‐
5640 https://github.com/python-babel/babel/pull/338)
5641
5642 • Messages: JavaScript extraction now supports dotted names, ES6 tem‐
5643 plate strings and JSX tags (‐
5644 https://github.com/python-babel/babel/pull/332)
5645
5646 • Messages: npgettext is recognized by default (‐
5647 https://github.com/python-babel/babel/pull/341)
5648
5649 • Messages: The CLI learned to accept multiple domains (‐
5650 https://github.com/python-babel/babel/pull/335)
5651
5652 • Messages: The extraction commands now accept filenames in addition to
5653 directories (https://github.com/python-babel/babel/pull/324)
5654
5655 • Units: A new API for unit formatting is implemented (‐
5656 https://github.com/python-babel/babel/pull/369)
5657
5658 Bugfixes
5659 • Core: Mixed-case locale IDs work more reliably (‐
5660 https://github.com/python-babel/babel/pull/361)
5661
5662 • Dates: S…S formats work correctly now (‐
5663 https://github.com/python-babel/babel/pull/360)
5664
5665 • Messages: All messages are now sorted correctly if sorting has been
5666 specified (https://github.com/python-babel/babel/pull/300)
5667
5668 • Messages: Fix the unexpected behavior caused by catalog header updat‐
5669 ing (e0e7ef1) (https://github.com/python-babel/babel/pull/320)
5670
5671 • Messages: Gettext operands are now generated correctly (‐
5672 https://github.com/python-babel/babel/pull/295)
5673
5674 • Messages: Message extraction has been taught to detect encodings bet‐
5675 ter (https://github.com/python-babel/babel/pull/274)
5676
5677 Version 2.2
5678 (Feature release, released on January 2nd 2016)
5679
5680 Bugfixes
5681 • General: Add __hash__ to Locale. (#303) (2aa8074)
5682
5683 • General: Allow files with BOM if they’re UTF-8 (#189) (da87edd)
5684
5685 • General: localedata directory is now locale-data (#109) (2d1882e)
5686
5687 • General: odict: Fix pop method (0a9e97e)
5688
5689 • General: Removed uses of datetime.date class from .dat files (#174)
5690 (94f6830)
5691
5692 • Messages: Fix plural selection for Chinese (531f666)
5693
5694 • Messages: Fix typo and add semicolon in plural_forms (5784501)
5695
5696 • Messages: Flatten NullTranslations.files into a list (ad11101)
5697
5698 • Times: FixedOffsetTimezone: fix display of negative offsets (d816803)
5699
5700 Features
5701 • CLDR: Update to CLDR 28 (#292) (9f7f4d0)
5702
5703 • General: Add __copy__ and __deepcopy__ to LazyProxy. (a1cc3f1)
5704
5705 • General: Add official support for Python 3.4 and 3.5
5706
5707 • General: Improve odict performance by making key search O(1)
5708 (6822b7f)
5709
5710 • Locale: Add an ordinal_form property to Locale (#270) (b3f3430)
5711
5712 • Locale: Add support for list formatting (37ce4fa, be6e23d)
5713
5714 • Locale: Check inheritance exceptions first (3ef0d6d)
5715
5716 • Messages: Allow file locations without line numbers (#279) (79bc781)
5717
5718 • Messages: Allow passing a callable to extract() (#289) (3f58516)
5719
5720 • Messages: Support ‘Language’ header field of PO files (#76) (3ce842b)
5721
5722 • Messages: Update catalog headers from templates (e0e7ef1)
5723
5724 • Numbers: Properly load and expose currency format types (#201)
5725 (df676ab)
5726
5727 • Numbers: Use cdecimal by default when available (b6169be)
5728
5729 • Numbers: Use the CLDR’s suggested number of decimals for format_cur‐
5730 rency (#139) (201ed50)
5731
5732 • Times: Add format_timedelta(format=’narrow’) support (edc5eb5)
5733
5734 Version 2.1
5735 (Bugfix/minor feature release, released on September 25th 2015)
5736
5737 • Parse and honour the locale inheritance exceptions (#97)
5738
5739 • Fix Locale.parse using global.dat incompatible types (#174)
5740
5741 • Fix display of negative offsets in FixedOffsetTimezone (#214)
5742
5743 • Improved odict performance which is used during localization file
5744 build, should improve compilation time for large projects
5745
5746 • Add support for “narrow” format for format_timedelta
5747
5748 • Add universal wheel support
5749
5750 • Support ‘Language’ header field in .PO files (fixes #76)
5751
5752 • Test suite enhancements (coverage, broken tests fixed, etc)
5753
5754 • Documentation updated
5755
5756 Version 2.0
5757 (Released on July 27th 2015, codename Second Coming)
5758
5759 • Added support for looking up currencies that belong to a territory
5760 through the babel.numbers.get_territory_currencies() function.
5761
5762 • Improved Python 3 support.
5763
5764 • Fixed some broken tests for timezone behavior.
5765
5766 • Improved various smaller things for dealing with dates.
5767
5768 Version 1.4
5769 (bugfix release, release date to be decided)
5770
5771 • Fixed a bug that caused deprecated territory codes not being con‐
5772 verted properly by the subtag resolving. This for instance showed up
5773 when trying to use und_UK as a language code which now properly re‐
5774 solves to en_GB.
5775
5776 • Fixed a bug that made it impossible to import the CLDR data from
5777 scratch on windows systems.
5778
5779 Version 1.3
5780 (bugfix release, released on July 29th 2013)
5781
5782 • Fixed a bug in likely-subtag resolving for some common locales. This
5783 primarily makes zh_CN work again which was broken due to how it was
5784 defined in the likely subtags combined with our broken resolving.
5785 This fixes #37.
5786
5787 • Fixed a bug that caused pybabel to break when writing to stdout on
5788 Python 3.
5789
5790 • Removed a stray print that was causing issues when writing to stdout
5791 for message catalogs.
5792
5793 Version 1.2
5794 (bugfix release, released on July 27th 2013)
5795
5796 • Included all tests in the tarball. Previously the include skipped
5797 past recursive folders.
5798
5799 • Changed how tests are invoked and added separate standalone test com‐
5800 mand. This simplifies testing of the package for linux distributors.
5801
5802 Version 1.1
5803 (bugfix release, released on July 27th 2013)
5804
5805 • added dummy version requirements for pytz so that it installs on pip
5806 1.4.
5807
5808 • Included tests in the tarball.
5809
5810 Version 1.0
5811 (Released on July 26th 2013, codename Revival)
5812
5813 • support python 2.6, 2.7, 3.3+ and pypy - drop all other versions
5814
5815 • use tox for testing on different pythons
5816
5817 • Added support for the locale plural rules defined by the CLDR.
5818
5819 • Added format_timedelta function to support localized formatting of
5820 relative times with strings such as “2 days” or “1 month” (ticket
5821 #126).
5822
5823 • Fixed negative offset handling of Catalog._set_mime_headers (ticket
5824 #165).
5825
5826 • Fixed the case where messages containing square brackets would break
5827 with an unpack error.
5828
5829 • updated to CLDR 23
5830
5831 • Make the CLDR import script work with Python 2.7.
5832
5833 • Fix various typos.
5834
5835 • Sort output of list-locales.
5836
5837 • Make the POT-Creation-Date of the catalog being updated equal to
5838 POT-Creation-Date of the template used to update (ticket #148).
5839
5840 • Use a more explicit error message if no option or argument (command)
5841 is passed to pybabel (ticket #81).
5842
5843 • Keep the PO-Revision-Date if it is not the default value (ticket
5844 #148).
5845
5846 • Make –no-wrap work by reworking –width’s default and mimic xgettext’s
5847 behaviour of always wrapping comments (ticket #145).
5848
5849 • Add –project and –version options for commandline (ticket #173).
5850
5851 • Add a __ne__() method to the Local class.
5852
5853 • Explicitly sort instead of using sorted() and don’t assume ordering
5854 (Jython compatibility).
5855
5856 • Removed ValueError raising for string formatting message checkers if
5857 the string does not contain any string formattings (ticket #150).
5858
5859 • Fix Serbian plural forms (ticket #213).
5860
5861 • Small speed improvement in format_date() (ticket #216).
5862
5863 • Fix so frontend.CommandLineInterface.run does not accumulate logging
5864 handlers (ticket #227, reported with initial patch by dfraser)
5865
5866 • Fix exception if environment contains an invalid locale setting (‐
5867 ticket #200)
5868
5869 • use cPickle instead of pickle for better performance (ticket #225)
5870
5871 • Only use bankers round algorithm as a tie breaker if there are two
5872 nearest numbers, round as usual if there is only one nearest number
5873 (ticket #267, patch by Martin)
5874
5875 • Allow disabling cache behaviour in LazyProxy (ticket #208, initial
5876 patch from Pedro Algarvio)
5877
5878 • Support for context-aware methods during message extraction (ticket
5879 #229, patch from David Rios)
5880
5881 • “init” and “update” commands support “–no-wrap” option (ticket #289)
5882
5883 • fix formatting of fraction in format_decimal() if the input value is
5884 a float with more than 7 significant digits (ticket #183)
5885
5886 • fix format_date() with datetime parameter (ticket #282, patch from
5887 Xavier Morel)
5888
5889 • fix format_decimal() with small Decimal values (ticket #214, patch
5890 from George Lund)
5891
5892 • fix handling of messages containing ‘\n’ (ticket #198)
5893
5894 • handle irregular multi-line msgstr (no “” as first line) gracefully
5895 (ticket #171)
5896
5897 • parse_decimal() now returns Decimals not floats, API change (ticket
5898 #178)
5899
5900 • no warnings when running setup.py without installed setuptools (‐
5901 ticket #262)
5902
5903 • modified Locale.__eq__ method so Locales are only equal if all of
5904 their attributes (language, territory, script, variant) are equal
5905
5906 • resort to hard-coded message extractors/checkers if pkg_resources is
5907 installed but no egg-info was found (ticket #230)
5908
5909 • format_time() and format_datetime() now accept also floats (ticket
5910 #242)
5911
5912 • add babel.support.NullTranslations class similar to gettext.Null‐
5913 Translations but with all of Babel’s new gettext methods (ticket
5914 #277)
5915
5916 • “init” and “update” commands support “–width” option (ticket #284)
5917
5918 • fix ‘input_dirs’ option for setuptools integration (ticket #232, ini‐
5919 tial patch by Étienne Bersac)
5920
5921 • ensure .mo file header contains the same information as the source
5922 .po file (ticket #199)
5923
5924 • added support for get_language_name() on the locale objects.
5925
5926 • added support for get_territory_name() on the locale objects.
5927
5928 • added support for get_script_name() on the locale objects.
5929
5930 • added pluralization support for currency names and added a ‘¤¤¤’ pat‐
5931 tern for currencies that includes the full name.
5932
5933 • depend on pytz now and wrap it nicer. This gives us improved support
5934 for things like timezone transitions and an overall nicer API.
5935
5936 • Added support for explicit charset to PO file reading.
5937
5938 • Added experimental Python 3 support.
5939
5940 • Added better support for returning timezone names.
5941
5942 • Don’t throw away a Catalog’s obsolete messages when updating it.
5943
5944 • Added basic likelySubtag resolving when doing locale parsing and no
5945 match can be found.
5946
5947 Version 0.9.6
5948 (released on March 17th 2011)
5949
5950 • Backport r493-494: documentation typo fixes.
5951
5952 • Make the CLDR import script work with Python 2.7.
5953
5954 • Fix various typos.
5955
5956 • Fixed Python 2.3 compatibility (ticket #146, ticket #233).
5957
5958 • Sort output of list-locales.
5959
5960 • Make the POT-Creation-Date of the catalog being updated equal to
5961 POT-Creation-Date of the template used to update (ticket #148).
5962
5963 • Use a more explicit error message if no option or argument (command)
5964 is passed to pybabel (ticket #81).
5965
5966 • Keep the PO-Revision-Date if it is not the default value (ticket
5967 #148).
5968
5969 • Make –no-wrap work by reworking –width’s default and mimic xgettext’s
5970 behaviour of always wrapping comments (ticket #145).
5971
5972 • Fixed negative offset handling of Catalog._set_mime_headers (ticket
5973 #165).
5974
5975 • Add –project and –version options for commandline (ticket #173).
5976
5977 • Add a __ne__() method to the Local class.
5978
5979 • Explicitly sort instead of using sorted() and don’t assume ordering
5980 (Python 2.3 and Jython compatibility).
5981
5982 • Removed ValueError raising for string formatting message checkers if
5983 the string does not contain any string formattings (ticket #150).
5984
5985 • Fix Serbian plural forms (ticket #213).
5986
5987 • Small speed improvement in format_date() (ticket #216).
5988
5989 • Fix number formatting for locales where CLDR specifies alt or draft
5990 items (ticket #217)
5991
5992 • Fix bad check in format_time (ticket #257, reported with patch and
5993 tests by jomae)
5994
5995 • Fix so frontend.CommandLineInterface.run does not accumulate logging
5996 handlers (ticket #227, reported with initial patch by dfraser)
5997
5998 • Fix exception if environment contains an invalid locale setting (‐
5999 ticket #200)
6000
6001 Version 0.9.5
6002 (released on April 6th 2010)
6003
6004 • Fixed the case where messages containing square brackets would break
6005 with an unpack error.
6006
6007 • Backport of r467: Fuzzy matching regarding plurals should NOT be
6008 checked against len(message.id) because this is always 2, instead,
6009 it’s should be checked against catalog.num_plurals (ticket #212).
6010
6011 Version 0.9.4
6012 (released on August 25th 2008)
6013
6014 • Currency symbol definitions that is defined with choice patterns in
6015 the CLDR data are no longer imported, so the symbol code will be used
6016 instead.
6017
6018 • Fixed quarter support in date formatting.
6019
6020 • Fixed a serious memory leak that was introduces by the support for
6021 CLDR aliases in 0.9.3 (ticket #128).
6022
6023 • Locale modifiers such as “@euro” are now stripped from locale identi‐
6024 fiers when parsing (ticket #136).
6025
6026 • The system locales “C” and “POSIX” are now treated as aliases for
6027 “en_US_POSIX”, for which the CLDR provides the appropriate data.
6028 Thanks to Manlio Perillo for the suggestion.
6029
6030 • Fixed JavaScript extraction for regular expression literals (ticket
6031 #138) and concatenated strings.
6032
6033 • The Translation class in babel.support can now manage catalogs with
6034 different message domains, and exposes the family of d*gettext func‐
6035 tions (ticket #137).
6036
6037 Version 0.9.3
6038 (released on July 9th 2008)
6039
6040 • Fixed invalid message extraction methods causing an UnboundLocalEr‐
6041 ror.
6042
6043 • Extraction method specification can now use a dot instead of the
6044 colon to separate module and function name (ticket #105).
6045
6046 • Fixed message catalog compilation for locales with more than two plu‐
6047 ral forms (ticket #95).
6048
6049 • Fixed compilation of message catalogs for locales with more than two
6050 plural forms where the translations were empty (ticket #97).
6051
6052 • The stripping of the comment tags in comments is optional now and is
6053 done for each line in a comment.
6054
6055 • Added a JavaScript message extractor.
6056
6057 • Updated to CLDR 1.6.
6058
6059 • Fixed timezone calculations when formatting datetime and time values.
6060
6061 • Added a get_plural function into the plurals module that returns the
6062 correct plural forms for a locale as tuple.
6063
6064 • Added support for alias definitions in the CLDR data files, meaning
6065 that the chance for items missing in certain locales should be
6066 greatly reduced (ticket #68).
6067
6068 Version 0.9.2
6069 (released on February 4th 2008)
6070
6071 • Fixed catalogs’ charset values not being recognized (ticket #66).
6072
6073 • Numerous improvements to the default plural forms.
6074
6075 • Fixed fuzzy matching when updating message catalogs (ticket #82).
6076
6077 • Fixed bug in catalog updating, that in some cases pulled in transla‐
6078 tions from different catalogs based on the same template.
6079
6080 • Location lines in PO files do no longer get wrapped at hyphens in
6081 file names (ticket #79).
6082
6083 • Fixed division by zero error in catalog compilation on empty catalogs
6084 (ticket #60).
6085
6086 Version 0.9.1
6087 (released on September 7th 2007)
6088
6089 • Fixed catalog updating when a message is merged that was previously
6090 simple but now has a plural form, for example by moving from gettext
6091 to ngettext, or vice versa.
6092
6093 • Fixed time formatting for 12 am and 12 pm.
6094
6095 • Fixed output encoding of the pybabel –list-locales command.
6096
6097 • MO files are now written in binary mode on windows (ticket #61).
6098
6099 Version 0.9
6100 (released on August 20th 2007)
6101
6102 • The new_catalog distutils command has been renamed to init_catalog
6103 for consistency with the command-line frontend.
6104
6105 • Added compilation of message catalogs to MO files (ticket #21).
6106
6107 • Added updating of message catalogs from POT files (ticket #22).
6108
6109 • Support for significant digits in number formatting.
6110
6111 • Apply proper “banker’s rounding” in number formatting in a
6112 cross-platform manner.
6113
6114 • The number formatting functions now also work with numbers repre‐
6115 sented by Python Decimal objects (ticket #53).
6116
6117 • Added extensible infrastructure for validating translation catalogs.
6118
6119 • Fixed the extractor not filtering out messages that didn’t validate
6120 against the keyword’s specification (ticket #39).
6121
6122 • Fixed the extractor raising an exception when encountering an empty
6123 string msgid. It now emits a warning to stderr.
6124
6125 • Numerous Python message extractor fixes: it now handles nested func‐
6126 tion calls within a gettext function call correctly, uses the correct
6127 line number for multi-line function calls, and other small fixes
6128 (tickets ticket #38 and ticket #39).
6129
6130 • Improved support for detecting Python string formatting fields in
6131 message strings (ticket #57).
6132
6133 • CLDR upgraded to the 1.5 release.
6134
6135 • Improved timezone formatting.
6136
6137 • Implemented scientific number formatting.
6138
6139 • Added mechanism to lookup locales by alias, for cases where browsers
6140 insist on including only the language code in the Accept-Language
6141 header, and sometimes even the incorrect language code.
6142
6143 Version 0.8.1
6144 (released on July 2nd 2007)
6145
6146 • default_locale() would fail when the value of the LANGUAGE environ‐
6147 ment variable contained multiple language codes separated by colon,
6148 as is explicitly allowed by the GNU gettext tools. As the default_lo‐
6149 cale() function is called at the module level in some modules, this
6150 bug would completely break importing these modules on systems where
6151 LANGUAGE is set that way.
6152
6153 • The character set specified in PO template files is now respected
6154 when creating new catalog files based on that template. This allows
6155 the use of characters outside the ASCII range in POT files (ticket
6156 #17).
6157
6158 • The default ordering of messages in generated POT files, which is
6159 based on the order those messages are found when walking the source
6160 tree, is no longer subject to differences between platforms; direc‐
6161 tory and file names are now always sorted alphabetically.
6162
6163 • The Python message extractor now respects the special encoding com‐
6164 ment to be able to handle files containing non-ASCII characters (‐
6165 ticket #23).
6166
6167 • Added N_ (gettext noop) to the extractor’s default keywords.
6168
6169 • Made locale string parsing more robust, and also take the script part
6170 into account (ticket #27).
6171
6172 • Added a function to list all locales for which locale data is avail‐
6173 able.
6174
6175 • Added a command-line option to the pybabel command which prints out
6176 all available locales (ticket #24).
6177
6178 • The name of the command-line script has been changed from just babel
6179 to pybabel to avoid a conflict with the OpenBabel project (ticket
6180 #34).
6181
6182 Version 0.8
6183 (released on June 20th 2007)
6184
6185 • First public release
6186
6187 License
6188 Babel is licensed under a three clause BSD License. It basically
6189 means: do whatever you want with it as long as the copyright in Babel
6190 sticks around, the conditions are not modified and the disclaimer is
6191 present. Furthermore you must not use the names of the authors to pro‐
6192 mote derivatives of the software without written consent.
6193
6194 The full license text can be found below (Babel License).
6195
6196 Authors
6197 Babel is written and maintained by the Babel team and various contribu‐
6198 tors:
6199
6200 • Aarni Koskela
6201
6202 • Christopher Lenz
6203
6204 • Armin Ronacher
6205
6206 • Alex Morega
6207
6208 • Lasse Schuirmann
6209
6210 • Felix Schwarz
6211
6212 • Pedro Algarvio
6213
6214 • Jeroen Ruigrok van der Werven
6215
6216 • Philip Jenvey
6217
6218 • benselme
6219
6220 • Isaac Jurado
6221
6222 • Tobias Bieniek
6223
6224 • Erick Wilder
6225
6226 • Michael Birtwell
6227
6228 • Jonas Borgström
6229
6230 • Kevin Deldycke
6231
6232 • Jon Dufresne
6233
6234 • Ville Skyttä
6235
6236 • Jun Omae
6237
6238 • Hugo
6239
6240 • Heungsub Lee
6241
6242 • Jakob Schnitzer
6243
6244 • Sachin Paliwal
6245
6246 • Alex Willmer
6247
6248 • Daniel Neuhäuser
6249
6250 • Hugo van Kemenade
6251
6252 • Miro Hrončok
6253
6254 • Cédric Krier
6255
6256 • Luke Plant
6257
6258 • Jennifer Wang
6259
6260 • Lukas Balaga
6261
6262 • sudheesh001
6263
6264 • Niklas Hambüchen
6265
6266 • Changaco
6267
6268 • Xavier Fernandez
6269
6270 • KO. Mattsson
6271
6272 • Sébastien Diemer
6273
6274 • alexbodn@gmail.com
6275
6276 • saurabhiiit
6277
6278 • srisankethu
6279
6280 • Erik Romijn
6281
6282 • Lukas B
6283
6284 • Ryan J Ollos
6285
6286 • Arturas Moskvinas
6287
6288 • Leonardo Pistone
6289
6290 • Hyunjun Kim
6291
6292 • Frank Harrison
6293
6294 • Nehal J Wani
6295
6296 • Mohamed Morsy
6297
6298 • Krzysztof Jagiełło
6299
6300 • Morgan Wahl
6301
6302 • farhan5900
6303
6304 • Sigurd Ljødal
6305
6306 • Andrii Oriekhov
6307
6308 • rachele-collin
6309
6310 • Lukas Winkler
6311
6312 • Juliette Monsel
6313
6314 • Álvaro Mondéjar Rubio
6315
6316 • ruro
6317
6318 • Alessio Bogon
6319
6320 • Nikiforov Konstantin
6321
6322 • Abdullah Javed Nesar
6323
6324 • Brad Martin
6325
6326 • Tyler Kennedy
6327
6328 • CyanNani123
6329
6330 • sebleblanc
6331
6332 • He Chen
6333
6334 • Steve (Gadget) Barnes
6335
6336 • Romuald Brunet
6337
6338 • Mario Frasca
6339
6340 • BT-sschmid
6341
6342 • Alberto Mardegan
6343
6344 • mondeja
6345
6346 • NotAFile
6347
6348 • Julien Palard
6349
6350 • Brian Cappello
6351
6352 • Serban Constantin
6353
6354 • Bryn Truscott
6355
6356 • Chris
6357
6358 • Charly C
6359
6360 • PTrottier
6361
6362 • xmo-odoo
6363
6364 • StevenJ
6365
6366 • Jungmo Ku
6367
6368 • Simeon Visser
6369
6370 • Narendra Vardi
6371
6372 • Stefane Fermigier
6373
6374 • Narayan Acharya
6375
6376 • François Magimel
6377
6378 • Wolfgang Doll
6379
6380 • Roy Williams
6381
6382 • Marc-André Dufresne
6383
6384 • Abhishek Tiwari
6385
6386 • David Baumgold
6387
6388 • Alex Kuzmenko
6389
6390 • Georg Schölly
6391
6392 • ldwoolley
6393
6394 • Rodrigo Ramírez Norambuena
6395
6396 • Jakub Wilk
6397
6398 • Roman Rader
6399
6400 • Max Shenfield
6401
6402 • Nicolas Grilly
6403
6404 • Kenny Root
6405
6406 • Adam Chainz
6407
6408 • Sébastien Fievet
6409
6410 • Anthony Sottile
6411
6412 • Yuriy Shatrov
6413
6414 • iamshubh22
6415
6416 • Sven Anderson
6417
6418 • Eoin Nugent
6419
6420 • Roman Imankulov
6421
6422 • David Stanek
6423
6424 • Roy Wellington Ⅳ
6425
6426 • Florian Schulze
6427
6428 • Todd M. Guerra
6429
6430 • Joseph Breihan
6431
6432 • Craig Loftus
6433
6434 • The Gitter Badger
6435
6436 • Régis Behmo
6437
6438 • Julen Ruiz Aizpuru
6439
6440 • astaric
6441
6442 • Felix Yan
6443
6444 • Philip_Tzou
6445
6446 • Jesús Espino
6447
6448 • Jeremy Weinstein
6449
6450 • James Page
6451
6452 • masklinn
6453
6454 • Sjoerd Langkemper
6455
6456 • Matt Iversen
6457
6458 • Alexander A. Dyshev
6459
6460 • Dirkjan Ochtman
6461
6462 • Nick Retallack
6463
6464 • Thomas Waldmann
6465
6466 • xen
6467
6468 Babel was previously developed under the Copyright of Edgewall Soft‐
6469 ware. The following copyright notice holds true for releases before
6470 2013: “Copyright (c) 2007 - 2011 by Edgewall Software”
6471
6472 In addition to the regular contributions Babel includes a fork of
6473 Lennart Regebro’s tzlocal that originally was licensed under the CC0
6474 license. The original copyright of that project is “Copyright 2013 by
6475 Lennart Regebro”.
6476
6477 General License Definitions
6478 The following section contains the full license texts for Babel and the
6479 documentation.
6480
6481 • “AUTHORS” hereby refers to all the authors listed in the Authors sec‐
6482 tion.
6483
6484 • The “Babel License” applies to all the sourcecode shipped as part of
6485 Babel (Babel itself as well as the examples and the unit tests) as
6486 well as documentation.
6487
6488 Babel License
6489 Copyright (c) 2013-2022 by the Babel Team, see AUTHORS for more infor‐
6490 mation.
6491
6492 All rights reserved.
6493
6494 Redistribution and use in source and binary forms, with or without mod‐
6495 ification, are permitted provided that the following conditions are
6496 met:
6497
6498 1. Redistributions of source code must retain the above copyright
6499 notice, this list of conditions and the following disclaimer.
6500
6501 2. Redistributions in binary form must reproduce the above copyright
6502 notice, this list of conditions and the following disclaimer in
6503 the documentation and/or other materials provided with the dis‐
6504 tribution.
6505
6506 3. The name of the author may not be used to endorse or promote
6507 products derived from this software without specific prior writ‐
6508 ten permission.
6509
6510 THIS SOFTWARE IS PROVIDED BY THE AUTHOR “AS IS” AND ANY EXPRESS OR IM‐
6511 PLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
6512 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
6513 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCI‐
6514 DENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
6515 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
6516 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
6517 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6518 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6519 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6520
6522 The Babel Team
6523
6525 2022, The Babel Team
6526
6527
6528
6529
65302.10 Jul 20, 2022 BABEL(1)