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_compact_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 compact_decimal_formats
1693 Locale patterns for compact decimal number formatting.
1694
1695 NOTE:
1696 The format of the value returned may change between
1697 Babel versions.
1698
1699 >>> Locale('en', 'US').compact_decimal_formats["short"]["one"]["1000"]
1700 <NumberPattern u'0K'>
1701
1702 property currencies
1703 Mapping of currency codes to translated currency names.
1704 This only returns the generic form of the currency name,
1705 not the count specific one. If an actual number is re‐
1706 quested use the babel.numbers.get_currency_name() func‐
1707 tion.
1708
1709 >>> Locale('en').currencies['COP']
1710 u'Colombian Peso'
1711 >>> Locale('de', 'DE').currencies['COP']
1712 u'Kolumbianischer Peso'
1713
1714 property currency_formats
1715 Locale patterns for currency number formatting.
1716
1717 NOTE:
1718 The format of the value returned may change between
1719 Babel versions.
1720
1721 >>> Locale('en', 'US').currency_formats['standard']
1722 <NumberPattern u'\xa4#,##0.00'>
1723 >>> Locale('en', 'US').currency_formats['accounting']
1724 <NumberPattern u'\xa4#,##0.00;(\xa4#,##0.00)'>
1725
1726 property currency_symbols
1727 Mapping of currency codes to symbols.
1728
1729 >>> Locale('en', 'US').currency_symbols['USD']
1730 u'$'
1731 >>> Locale('es', 'CO').currency_symbols['USD']
1732 u'US$'
1733
1734 property date_formats
1735 Locale patterns for date formatting.
1736
1737 NOTE:
1738 The format of the value returned may change between
1739 Babel versions.
1740
1741 >>> Locale('en', 'US').date_formats['short']
1742 <DateTimePattern u'M/d/yy'>
1743 >>> Locale('fr', 'FR').date_formats['long']
1744 <DateTimePattern u'd MMMM y'>
1745
1746 property datetime_formats
1747 Locale patterns for datetime formatting.
1748
1749 NOTE:
1750 The format of the value returned may change between
1751 Babel versions.
1752
1753 >>> Locale('en').datetime_formats['full']
1754 u"{1} 'at' {0}"
1755 >>> Locale('th').datetime_formats['medium']
1756 u'{1} {0}'
1757
1758 property datetime_skeletons
1759 Locale patterns for formatting parts of a datetime.
1760
1761 >>> Locale('en').datetime_skeletons['MEd']
1762 <DateTimePattern u'E, M/d'>
1763 >>> Locale('fr').datetime_skeletons['MEd']
1764 <DateTimePattern u'E dd/MM'>
1765 >>> Locale('fr').datetime_skeletons['H']
1766 <DateTimePattern u"HH 'h'">
1767
1768 property day_period_rules
1769 Day period rules for the locale. Used by get_period_id.
1770
1771 property day_periods
1772 Locale display names for various day periods (not neces‐
1773 sarily only AM/PM).
1774
1775 These are not meant to be used without the relevant
1776 day_period_rules.
1777
1778 property days
1779 Locale display names for weekdays.
1780
1781 >>> Locale('de', 'DE').days['format']['wide'][3]
1782 u'Donnerstag'
1783
1784 property decimal_formats
1785 Locale patterns for decimal number formatting.
1786
1787 NOTE:
1788 The format of the value returned may change between
1789 Babel versions.
1790
1791 >>> Locale('en', 'US').decimal_formats[None]
1792 <NumberPattern u'#,##0.###'>
1793
1794 classmethod default(category=None, aliases={'ar': 'ar_SY', 'bg':
1795 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 'da':
1796 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es':
1797 'es_ES', 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr':
1798 'fr_FR', 'gl': 'gl_ES', 'he': 'he_IL', 'hu': 'hu_HU', 'id':
1799 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 'ja': 'ja_JP', 'km':
1800 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk':
1801 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl':
1802 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk':
1803 'sk_SK', 'sl': 'sl_SI', 'sv': 'sv_SE', 'th': 'th_TH', 'tr':
1804 'tr_TR', 'uk': 'uk_UA'})
1805 Return the system default locale for the specified cate‐
1806 gory.
1807
1808 >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
1809 ... os.environ[name] = ''
1810 >>> os.environ['LANG'] = 'fr_FR.UTF-8'
1811 >>> Locale.default('LC_MESSAGES')
1812 Locale('fr', territory='FR')
1813
1814 The following fallbacks to the variable are always con‐
1815 sidered:
1816
1817 • LANGUAGE
1818
1819 • LC_ALL
1820
1821 • LC_CTYPE
1822
1823 • LANG
1824
1825 Parameters
1826
1827 • category – one of the LC_XXX environment vari‐
1828 able names
1829
1830 • aliases – a dictionary of aliases for locale
1831 identifiers
1832
1833 property display_name
1834 The localized display name of the locale.
1835
1836 >>> Locale('en').display_name
1837 u'English'
1838 >>> Locale('en', 'US').display_name
1839 u'English (United States)'
1840 >>> Locale('sv').display_name
1841 u'svenska'
1842
1843 Type unicode
1844
1845 property english_name
1846 The english display name of the locale.
1847
1848 >>> Locale('de').english_name
1849 u'German'
1850 >>> Locale('de', 'DE').english_name
1851 u'German (Germany)'
1852
1853 Type unicode
1854
1855 property eras
1856 Locale display names for eras.
1857
1858 NOTE:
1859 The format of the value returned may change between
1860 Babel versions.
1861
1862 >>> Locale('en', 'US').eras['wide'][1]
1863 u'Anno Domini'
1864 >>> Locale('en', 'US').eras['abbreviated'][0]
1865 u'BC'
1866
1867 property first_week_day
1868 The first day of a week, with 0 being Monday.
1869
1870 >>> Locale('de', 'DE').first_week_day
1871 0
1872 >>> Locale('en', 'US').first_week_day
1873 6
1874
1875 get_display_name(locale=None)
1876 Return the display name of the locale using the given lo‐
1877 cale.
1878
1879 The display name will include the language, territory,
1880 script, and variant, if those are specified.
1881
1882 >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
1883 u'Chinese (Simplified, China)'
1884
1885 Parameters
1886 locale – the locale to use
1887
1888 get_language_name(locale=None)
1889 Return the language of this locale in the given locale.
1890
1891 >>> Locale('zh', 'CN', script='Hans').get_language_name('de')
1892 u'Chinesisch'
1893
1894 New in version 1.0.
1895
1896
1897 Parameters
1898 locale – the locale to use
1899
1900 get_script_name(locale=None)
1901 Return the script name in the given locale.
1902
1903 get_territory_name(locale=None)
1904 Return the territory name in the given locale.
1905
1906 property interval_formats
1907 Locale patterns for interval formatting.
1908
1909 NOTE:
1910 The format of the value returned may change between
1911 Babel versions.
1912
1913 How to format date intervals in Finnish when the day is
1914 the smallest changing component:
1915
1916 >>> Locale('fi_FI').interval_formats['MEd']['d']
1917 [u'E d. – ', u'E d.M.']
1918
1919 SEE ALSO:
1920 The primary API to use this data is
1921 babel.dates.format_interval().
1922
1923 Return type
1924 dict[str, dict[str, list[str]]]
1925
1926 language
1927 the language code
1928
1929 property language_name
1930 The localized language name of the locale.
1931
1932 >>> Locale('en', 'US').language_name
1933 u'English'
1934
1935 property languages
1936 Mapping of language codes to translated language names.
1937
1938 >>> Locale('de', 'DE').languages['ja']
1939 u'Japanisch'
1940
1941 See ISO 639 for more information.
1942
1943 property list_patterns
1944 Patterns for generating lists
1945
1946 NOTE:
1947 The format of the value returned may change between
1948 Babel versions.
1949
1950 >>> Locale('en').list_patterns['standard']['start']
1951 u'{0}, {1}'
1952 >>> Locale('en').list_patterns['standard']['end']
1953 u'{0}, and {1}'
1954 >>> Locale('en_GB').list_patterns['standard']['end']
1955 u'{0} and {1}'
1956
1957 property measurement_systems
1958 Localized names for various measurement systems.
1959
1960 >>> Locale('fr', 'FR').measurement_systems['US']
1961 u'am\xe9ricain'
1962 >>> Locale('en', 'US').measurement_systems['US']
1963 u'US'
1964
1965 property meta_zones
1966 Locale display names for meta time zones.
1967
1968 Meta time zones are basically groups of different Olson
1969 time zones that have the same GMT offset and daylight
1970 savings time.
1971
1972 NOTE:
1973 The format of the value returned may change between
1974 Babel versions.
1975
1976 >>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
1977 u'Central European Summer Time'
1978
1979 New in version 0.9.
1980
1981
1982 property min_week_days
1983 The minimum number of days in a week so that the week is
1984 counted as the first week of a year or month.
1985
1986 >>> Locale('de', 'DE').min_week_days
1987 4
1988
1989 property months
1990 Locale display names for months.
1991
1992 >>> Locale('de', 'DE').months['format']['wide'][10]
1993 u'Oktober'
1994
1995 classmethod negotiate(preferred, available, sep='_',
1996 aliases={'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca':
1997 'ca_ES', 'cs': 'cs_CZ', 'da': 'da_DK', 'de': 'de_DE', 'el':
1998 'el_GR', 'en': 'en_US', 'es': 'es_ES', 'et': 'et_EE', 'fa':
1999 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES', 'he':
2000 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it':
2001 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt':
2002 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn':
2003 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro':
2004 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv':
2005 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'})
2006 Find the best match between available and requested lo‐
2007 cale strings.
2008
2009 >>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
2010 Locale('de', territory='DE')
2011 >>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
2012 Locale('de')
2013 >>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
2014
2015 You can specify the character used in the locale identi‐
2016 fiers to separate the differnet components. This separa‐
2017 tor is applied to both lists. Also, case is ignored in
2018 the comparison:
2019
2020 >>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
2021 Locale('de', territory='DE')
2022
2023 Parameters
2024
2025 • preferred – the list of locale identifers pre‐
2026 ferred by the user
2027
2028 • available – the list of locale identifiers
2029 available
2030
2031 • aliases – a dictionary of aliases for locale
2032 identifiers
2033
2034 property number_symbols
2035 Symbols used in number formatting.
2036
2037 NOTE:
2038 The format of the value returned may change between
2039 Babel versions.
2040
2041 >>> Locale('fr', 'FR').number_symbols['decimal']
2042 u','
2043
2044 property ordinal_form
2045 Plural rules for the locale.
2046
2047 >>> Locale('en').ordinal_form(1)
2048 'one'
2049 >>> Locale('en').ordinal_form(2)
2050 'two'
2051 >>> Locale('en').ordinal_form(3)
2052 'few'
2053 >>> Locale('fr').ordinal_form(2)
2054 'other'
2055 >>> Locale('ru').ordinal_form(100)
2056 'other'
2057
2058 classmethod parse(identifier, sep='_', resolve_likely_sub‐
2059 tags=True)
2060 Create a Locale instance for the given locale identifier.
2061
2062 >>> l = Locale.parse('de-DE', sep='-')
2063 >>> l.display_name
2064 u'Deutsch (Deutschland)'
2065
2066 If the identifier parameter is not a string, but actually
2067 a Locale object, that object is returned:
2068
2069 >>> Locale.parse(l)
2070 Locale('de', territory='DE')
2071
2072 This also can perform resolving of likely subtags which
2073 it does by default. This is for instance useful to fig‐
2074 ure out the most likely locale for a territory you can
2075 use 'und' as the language tag:
2076
2077 >>> Locale.parse('und_AT')
2078 Locale('de', territory='AT')
2079
2080 Parameters
2081
2082 • identifier – the locale identifier string
2083
2084 • sep – optional component separator
2085
2086 • resolve_likely_subtags – if this is specified
2087 then a locale will have its likely subtag re‐
2088 solved if the locale otherwise does not exist.
2089 For instance zh_TW by itself is not a locale
2090 that exists but Babel can automatically expand
2091 it to the full form of zh_hant_TW. Note that
2092 this expansion is only taking place if no locale
2093 exists otherwise. For instance there is a lo‐
2094 cale en that can exist by itself.
2095
2096 Raises
2097
2098 • ValueError – if the string does not appear to be
2099 a valid locale identifier
2100
2101 • UnknownLocaleError – if no locale data is avail‐
2102 able for the requested locale
2103
2104 property percent_formats
2105 Locale patterns for percent number formatting.
2106
2107 NOTE:
2108 The format of the value returned may change between
2109 Babel versions.
2110
2111 >>> Locale('en', 'US').percent_formats[None]
2112 <NumberPattern u'#,##0%'>
2113
2114 property periods
2115 Locale display names for day periods (AM/PM).
2116
2117 >>> Locale('en', 'US').periods['am']
2118 u'AM'
2119
2120 property plural_form
2121 Plural rules for the locale.
2122
2123 >>> Locale('en').plural_form(1)
2124 'one'
2125 >>> Locale('en').plural_form(0)
2126 'other'
2127 >>> Locale('fr').plural_form(0)
2128 'one'
2129 >>> Locale('ru').plural_form(100)
2130 'many'
2131
2132 property quarters
2133 Locale display names for quarters.
2134
2135 >>> Locale('de', 'DE').quarters['format']['wide'][1]
2136 u'1. Quartal'
2137
2138 property scientific_formats
2139 Locale patterns for scientific number formatting.
2140
2141 NOTE:
2142 The format of the value returned may change between
2143 Babel versions.
2144
2145 >>> Locale('en', 'US').scientific_formats[None]
2146 <NumberPattern u'#E0'>
2147
2148 script the script code
2149
2150 property script_name
2151 The localized script name of the locale if available.
2152
2153 >>> Locale('sr', 'ME', script='Latn').script_name
2154 u'latinica'
2155
2156 property scripts
2157 Mapping of script codes to translated script names.
2158
2159 >>> Locale('en', 'US').scripts['Hira']
2160 u'Hiragana'
2161
2162 See ISO 15924 for more information.
2163
2164 property territories
2165 Mapping of script codes to translated script names.
2166
2167 >>> Locale('es', 'CO').territories['DE']
2168 u'Alemania'
2169
2170 See ISO 3166 for more information.
2171
2172 territory
2173 the territory (country or region) code
2174
2175 property territory_name
2176 The localized territory name of the locale if available.
2177
2178 >>> Locale('de', 'DE').territory_name
2179 u'Deutschland'
2180
2181 property text_direction
2182 The text direction for the language in CSS short-hand
2183 form.
2184
2185 >>> Locale('de', 'DE').text_direction
2186 'ltr'
2187 >>> Locale('ar', 'SA').text_direction
2188 'rtl'
2189
2190 property time_formats
2191 Locale patterns for time formatting.
2192
2193 NOTE:
2194 The format of the value returned may change between
2195 Babel versions.
2196
2197 >>> Locale('en', 'US').time_formats['short']
2198 <DateTimePattern u'h:mm a'>
2199 >>> Locale('fr', 'FR').time_formats['long']
2200 <DateTimePattern u'HH:mm:ss z'>
2201
2202 property time_zones
2203 Locale display names for time zones.
2204
2205 NOTE:
2206 The format of the value returned may change between
2207 Babel versions.
2208
2209 >>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
2210 u'British Summer Time'
2211 >>> Locale('en', 'US').time_zones['America/St_Johns']['city']
2212 u'St. John’s'
2213
2214 property unit_display_names
2215 Display names for units of measurement.
2216
2217 SEE ALSO:
2218 You may want to use babel.units.get_unit_name() in‐
2219 stead.
2220
2221 NOTE:
2222 The format of the value returned may change between
2223 Babel versions.
2224
2225 variant
2226 the variant code
2227
2228 property variants
2229 Mapping of script codes to translated script names.
2230
2231 >>> Locale('de', 'DE').variants['1901']
2232 u'Alte deutsche Rechtschreibung'
2233
2234 property weekend_end
2235 The day the weekend ends, with 0 being Monday.
2236
2237 >>> Locale('de', 'DE').weekend_end
2238 6
2239
2240 property weekend_start
2241 The day the weekend starts, with 0 being Monday.
2242
2243 >>> Locale('de', 'DE').weekend_start
2244 5
2245
2246 property zone_formats
2247 Patterns related to the formatting of time zones.
2248
2249 NOTE:
2250 The format of the value returned may change between
2251 Babel versions.
2252
2253 >>> Locale('en', 'US').zone_formats['fallback']
2254 u'%(1)s (%(0)s)'
2255 >>> Locale('pt', 'BR').zone_formats['region']
2256 u'Hor\xe1rio %s'
2257
2258 New in version 0.9.
2259
2260
2261 babel.core.default_locale(category=None, aliases={'ar': 'ar_SY', 'bg':
2262 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 'da': 'da_DK',
2263 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES', 'et':
2264 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
2265 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it':
2266 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT',
2267 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no':
2268 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU',
2269 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv': 'sv_SE', 'th': 'th_TH', 'tr':
2270 'tr_TR', 'uk': 'uk_UA'})
2271 Returns the system default locale for a given category, based on
2272 environment variables.
2273
2274 >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
2275 ... os.environ[name] = ''
2276 >>> os.environ['LANG'] = 'fr_FR.UTF-8'
2277 >>> default_locale('LC_MESSAGES')
2278 'fr_FR'
2279
2280 The “C” or “POSIX” pseudo-locales are treated as aliases for the
2281 “en_US_POSIX” locale:
2282
2283 >>> os.environ['LC_MESSAGES'] = 'POSIX'
2284 >>> default_locale('LC_MESSAGES')
2285 'en_US_POSIX'
2286
2287 The following fallbacks to the variable are always considered:
2288
2289 • LANGUAGE
2290
2291 • LC_ALL
2292
2293 • LC_CTYPE
2294
2295 • LANG
2296
2297 Parameters
2298
2299 • category – one of the LC_XXX environment variable names
2300
2301 • aliases – a dictionary of aliases for locale identi‐
2302 fiers
2303
2304 babel.core.negotiate_locale(preferred, available, sep='_',
2305 aliases={'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES',
2306 'cs': 'cs_CZ', 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en':
2307 'en_US', 'es': 'es_ES', 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI',
2308 'fr': 'fr_FR', 'gl': 'gl_ES', 'he': 'he_IL', 'hu': 'hu_HU', 'id':
2309 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH',
2310 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl':
2311 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT',
2312 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv':
2313 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'})
2314 Find the best match between available and requested locale
2315 strings.
2316
2317 >>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
2318 'de_DE'
2319 >>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
2320 'de'
2321
2322 Case is ignored by the algorithm, the result uses the case of
2323 the preferred locale identifier:
2324
2325 >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
2326 'de_DE'
2327
2328 >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
2329 'de_DE'
2330
2331 By default, some web browsers unfortunately do not include the
2332 territory in the locale identifier for many locales, and some
2333 don’t even allow the user to easily add the territory. So while
2334 you may prefer using qualified locale identifiers in your
2335 web-application, they would not normally match the language-only
2336 locale sent by such browsers. To workaround that, this function
2337 uses a default mapping of commonly used language-only locale
2338 identifiers to identifiers including the territory:
2339
2340 >>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
2341 'ja_JP'
2342
2343 Some browsers even use an incorrect or outdated language code,
2344 such as “no” for Norwegian, where the correct locale identifier
2345 would actually be “nb_NO” (Bokmål) or “nn_NO” (Nynorsk). The
2346 aliases are intended to take care of such cases, too:
2347
2348 >>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
2349 'nb_NO'
2350
2351 You can override this default mapping by passing a different
2352 aliases dictionary to this function, or you can bypass the be‐
2353 havior althogher by setting the aliases parameter to None.
2354
2355 Parameters
2356
2357 • preferred – the list of locale strings preferred by the
2358 user
2359
2360 • available – the list of locale strings available
2361
2362 • sep – character that separates the different parts of
2363 the locale strings
2364
2365 • aliases – a dictionary of aliases for locale identi‐
2366 fiers
2367
2368 Exceptions
2369 exception babel.core.UnknownLocaleError(identifier)
2370 Exception thrown when a locale is requested for which no locale
2371 data is available.
2372
2373 identifier
2374 The identifier of the locale that could not be found.
2375
2376 Utility Functions
2377 babel.core.get_global(key)
2378 Return the dictionary for the given key in the global data.
2379
2380 The global data is stored in the babel/global.dat file and con‐
2381 tains information independent of individual locales.
2382
2383 >>> get_global('zone_aliases')['UTC']
2384 u'Etc/UTC'
2385 >>> get_global('zone_territories')['Europe/Berlin']
2386 u'DE'
2387
2388 The keys available are:
2389
2390 • all_currencies
2391
2392 • currency_fractions
2393
2394 • language_aliases
2395
2396 • likely_subtags
2397
2398 • parent_exceptions
2399
2400 • script_aliases
2401
2402 • territory_aliases
2403
2404 • territory_currencies
2405
2406 • territory_languages
2407
2408 • territory_zones
2409
2410 • variant_aliases
2411
2412 • windows_zone_mapping
2413
2414 • zone_aliases
2415
2416 • zone_territories
2417
2418 NOTE:
2419 The internal structure of the data may change between ver‐
2420 sions.
2421
2422 New in version 0.9.
2423
2424
2425 Parameters
2426 key – the data key
2427
2428 babel.core.parse_locale(identifier, sep='_')
2429 Parse a locale identifier into a tuple of the form (language,
2430 territory, script, variant).
2431
2432 >>> parse_locale('zh_CN')
2433 ('zh', 'CN', None, None)
2434 >>> parse_locale('zh_Hans_CN')
2435 ('zh', 'CN', 'Hans', None)
2436 >>> parse_locale('ca_es_valencia')
2437 ('ca', 'ES', None, 'VALENCIA')
2438 >>> parse_locale('en_150')
2439 ('en', '150', None, None)
2440 >>> parse_locale('en_us_posix')
2441 ('en', 'US', None, 'POSIX')
2442
2443 The default component separator is “_”, but a different separa‐
2444 tor can be specified using the sep parameter:
2445
2446 >>> parse_locale('zh-CN', sep='-')
2447 ('zh', 'CN', None, None)
2448
2449 If the identifier cannot be parsed into a locale, a ValueError
2450 exception is raised:
2451
2452 >>> parse_locale('not_a_LOCALE_String')
2453 Traceback (most recent call last):
2454 ...
2455 ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
2456
2457 Encoding information and locale modifiers are removed from the
2458 identifier:
2459
2460 >>> parse_locale('it_IT@euro')
2461 ('it', 'IT', None, None)
2462 >>> parse_locale('en_US.UTF-8')
2463 ('en', 'US', None, None)
2464 >>> parse_locale('de_DE.iso885915@euro')
2465 ('de', 'DE', None, None)
2466
2467 See RFC 4646 for more information.
2468
2469 Parameters
2470
2471 • identifier – the locale identifier string
2472
2473 • sep – character that separates the different components
2474 of the locale identifier
2475
2476 Raises ValueError – if the string does not appear to be a valid
2477 locale identifier
2478
2479 babel.core.get_locale_identifier(tup, sep='_')
2480 The reverse of parse_locale(). It creates a locale identifier
2481 out of a (language, territory, script, variant) tuple. Items
2482 can be set to None and trailing Nones can also be left out of
2483 the tuple.
2484
2485 >>> get_locale_identifier(('de', 'DE', None, '1999'))
2486 'de_DE_1999'
2487
2488 New in version 1.0.
2489
2490
2491 Parameters
2492
2493 • tup – the tuple as returned by parse_locale().
2494
2495 • sep – the separator for the identifier.
2496
2497 Date and Time
2498 The date and time functionality provided by Babel lets you format stan‐
2499 dard Python datetime, date and time objects and work with timezones.
2500
2501 Date and Time Formatting
2502 babel.dates.format_datetime(datetime=None, format='medium', tz‐
2503 info=None, locale=default_locale('LC_TIME'))
2504 Return a date formatted according to the given pattern.
2505
2506 >>> dt = datetime(2007, 4, 1, 15, 30)
2507 >>> format_datetime(dt, locale='en_US')
2508 u'Apr 1, 2007, 3:30:00 PM'
2509
2510 For any pattern requiring the display of the time-zone, the
2511 third-party pytz package is needed to explicitly specify the
2512 time-zone:
2513
2514 >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
2515 ... locale='fr_FR')
2516 u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
2517 >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
2518 ... tzinfo=get_timezone('US/Eastern'), locale='en')
2519 u'2007.04.01 AD at 11:30:00 EDT'
2520
2521 Parameters
2522
2523 • datetime – the datetime object; if None, the current
2524 date and time is used
2525
2526 • format – one of “full”, “long”, “medium”, or “short”,
2527 or a custom date/time pattern
2528
2529 • tzinfo – the timezone to apply to the time for display
2530
2531 • locale – a Locale object or a locale identifier
2532
2533 babel.dates.format_date(date=None, format='medium', locale=default_lo‐
2534 cale('LC_TIME'))
2535 Return a date formatted according to the given pattern.
2536
2537 >>> d = date(2007, 4, 1)
2538 >>> format_date(d, locale='en_US')
2539 u'Apr 1, 2007'
2540 >>> format_date(d, format='full', locale='de_DE')
2541 u'Sonntag, 1. April 2007'
2542
2543 If you don’t want to use the locale default formats, you can
2544 specify a custom date pattern:
2545
2546 >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
2547 u"Sun, Apr 1, '07"
2548
2549 Parameters
2550
2551 • date – the date or datetime object; if None, the cur‐
2552 rent date is used
2553
2554 • format – one of “full”, “long”, “medium”, or “short”,
2555 or a custom date/time pattern
2556
2557 • locale – a Locale object or a locale identifier
2558
2559 babel.dates.format_time(time=None, format='medium', tzinfo=None, lo‐
2560 cale=default_locale('LC_TIME'))
2561 Return a time formatted according to the given pattern.
2562
2563 >>> t = time(15, 30)
2564 >>> format_time(t, locale='en_US')
2565 u'3:30:00 PM'
2566 >>> format_time(t, format='short', locale='de_DE')
2567 u'15:30'
2568
2569 If you don’t want to use the locale default formats, you can
2570 specify a custom time pattern:
2571
2572 >>> format_time(t, "hh 'o''clock' a", locale='en')
2573 u"03 o'clock PM"
2574
2575 For any pattern requiring the display of the time-zone a time‐
2576 zone has to be specified explicitly:
2577
2578 >>> t = datetime(2007, 4, 1, 15, 30)
2579 >>> tzinfo = get_timezone('Europe/Paris')
2580 >>> t = tzinfo.localize(t)
2581 >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
2582 u'15:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
2583 >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
2584 ... locale='en')
2585 u"09 o'clock AM, Eastern Daylight Time"
2586
2587 As that example shows, when this function gets passed a date‐
2588 time.datetime value, the actual time in the formatted string is
2589 adjusted to the timezone specified by the tzinfo parameter. If
2590 the datetime is “naive” (i.e. it has no associated timezone in‐
2591 formation), it is assumed to be in UTC.
2592
2593 These timezone calculations are not performed if the value is of
2594 type datetime.time, as without date information there’s no way
2595 to determine what a given time would translate to in a different
2596 timezone without information about whether daylight savings time
2597 is in effect or not. This means that time values are left as-is,
2598 and the value of the tzinfo parameter is only used to display
2599 the timezone name if needed:
2600
2601 >>> t = time(15, 30)
2602 >>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
2603 ... locale='fr_FR')
2604 u'15:30:00 heure normale d\u2019Europe centrale'
2605 >>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
2606 ... locale='en_US')
2607 u'3:30:00 PM Eastern Standard Time'
2608
2609 Parameters
2610
2611 • time – the time or datetime object; if None, the cur‐
2612 rent time in UTC is used
2613
2614 • format – one of “full”, “long”, “medium”, or “short”,
2615 or a custom date/time pattern
2616
2617 • tzinfo – the time-zone to apply to the time for display
2618
2619 • locale – a Locale object or a locale identifier
2620
2621 babel.dates.format_timedelta(delta, granularity='second', thresh‐
2622 old=.85, add_direction=False, format='long', locale=default_lo‐
2623 cale('LC_TIME'))
2624 Return a time delta according to the rules of the given locale.
2625
2626 >>> format_timedelta(timedelta(weeks=12), locale='en_US')
2627 u'3 months'
2628 >>> format_timedelta(timedelta(seconds=1), locale='es')
2629 u'1 segundo'
2630
2631 The granularity parameter can be provided to alter the lowest
2632 unit presented, which defaults to a second.
2633
2634 >>> format_timedelta(timedelta(hours=3), granularity='day',
2635 ... locale='en_US')
2636 u'1 day'
2637
2638 The threshold parameter can be used to determine at which value
2639 the presentation switches to the next higher unit. A higher
2640 threshold factor means the presentation will switch later. For
2641 example:
2642
2643 >>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
2644 u'1 day'
2645 >>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
2646 u'23 hours'
2647
2648 In addition directional information can be provided that informs
2649 the user if the date is in the past or in the future:
2650
2651 >>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
2652 u'in 1 hour'
2653 >>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
2654 u'1 hour ago'
2655
2656 The format parameter controls how compact or wide the presenta‐
2657 tion is:
2658
2659 >>> format_timedelta(timedelta(hours=3), format='short', locale='en')
2660 u'3 hr'
2661 >>> format_timedelta(timedelta(hours=3), format='narrow', locale='en')
2662 u'3h'
2663
2664 Parameters
2665
2666 • delta – a timedelta object representing the time dif‐
2667 ference to format, or the delta in seconds as an int
2668 value
2669
2670 • granularity – determines the smallest unit that should
2671 be displayed, the value can be one of “year”, “month”,
2672 “week”, “day”, “hour”, “minute” or “second”
2673
2674 • threshold – factor that determines at which point the
2675 presentation switches to the next higher unit
2676
2677 • add_direction – if this flag is set to True the return
2678 value will include directional information. For in‐
2679 stance a positive timedelta will include the informa‐
2680 tion about it being in the future, a negative will be
2681 information about the value being in the past.
2682
2683 • format – the format, can be “narrow”, “short” or
2684 “long”. ( “medium” is deprecated, currently converted
2685 to “long” to maintain compatibility)
2686
2687 • locale – a Locale object or a locale identifier
2688
2689 babel.dates.format_skeleton(skeleton, datetime=None, tzinfo=None,
2690 fuzzy=True, locale=default_locale('LC_TIME'))
2691 Return a time and/or date formatted according to the given pat‐
2692 tern.
2693
2694 The skeletons are defined in the CLDR data and provide more
2695 flexibility than the simple short/long/medium formats, but are a
2696 bit harder to use. The are defined using the date/time symbols
2697 without order or punctuation and map to a suitable format for
2698 the given locale.
2699
2700 >>> t = datetime(2007, 4, 1, 15, 30)
2701 >>> format_skeleton('MMMEd', t, locale='fr')
2702 u'dim. 1 avr.'
2703 >>> format_skeleton('MMMEd', t, locale='en')
2704 u'Sun, Apr 1'
2705 >>> format_skeleton('yMMd', t, locale='fi') # yMMd is not in the Finnish locale; yMd gets used
2706 u'1.4.2007'
2707 >>> format_skeleton('yMMd', t, fuzzy=False, locale='fi') # yMMd is not in the Finnish locale, an error is thrown
2708 Traceback (most recent call last):
2709 ...
2710 KeyError: yMMd
2711
2712 After the skeleton is resolved to a pattern format_datetime is
2713 called so all timezone processing etc is the same as for that.
2714
2715 Parameters
2716
2717 • skeleton – A date time skeleton as defined in the cldr
2718 data.
2719
2720 • datetime – the time or datetime object; if None, the
2721 current time in UTC is used
2722
2723 • tzinfo – the time-zone to apply to the time for display
2724
2725 • fuzzy – If the skeleton is not found, allow choosing a
2726 skeleton that’s close enough to it.
2727
2728 • locale – a Locale object or a locale identifier
2729
2730 babel.dates.format_interval(start, end, skeleton=None, tzinfo=None,
2731 fuzzy=True, locale=default_locale('LC_TIME'))
2732 Format an interval between two instants according to the lo‐
2733 cale’s rules.
2734
2735 >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
2736 u'15.–17.1.2016'
2737
2738 >>> format_interval(time(12, 12), time(16, 16), "Hm", locale="en_GB")
2739 '12:12–16:16'
2740
2741 >>> format_interval(time(5, 12), time(16, 16), "hm", locale="en_US")
2742 '5:12 AM – 4:16 PM'
2743
2744 >>> format_interval(time(16, 18), time(16, 24), "Hm", locale="it")
2745 '16:18–16:24'
2746
2747 If the start instant equals the end instant, the interval is
2748 formatted like the instant.
2749
2750 >>> format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
2751 '16:18'
2752
2753 Unknown skeletons fall back to “default” formatting.
2754
2755 >>> format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
2756 '2015/01/01~2017/01/01'
2757
2758 >>> format_interval(time(16, 18), time(16, 24), "xxx", locale="ja")
2759 '16:18:00~16:24:00'
2760
2761 >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
2762 '15.01.2016 – 17.01.2016'
2763
2764 Parameters
2765
2766 • start – First instant (datetime/date/time)
2767
2768 • end – Second instant (datetime/date/time)
2769
2770 • skeleton – The “skeleton format” to use for formatting.
2771
2772 • tzinfo – tzinfo to use (if none is already attached)
2773
2774 • fuzzy – If the skeleton is not found, allow choosing a
2775 skeleton that’s close enough to it.
2776
2777 • locale – A locale object or identifier.
2778
2779 Returns
2780 Formatted interval
2781
2782 Timezone Functionality
2783 babel.dates.get_timezone(zone=None)
2784 Looks up a timezone by name and returns it. The timezone object
2785 returned comes from pytz and corresponds to the tzinfo interface
2786 and can be used with all of the functions of Babel that operate
2787 with dates.
2788
2789 If a timezone is not known a LookupError is raised. If zone is
2790 None a local zone object is returned.
2791
2792 Parameters
2793 zone – the name of the timezone to look up. If a time‐
2794 zone object itself is passed in, mit’s returned un‐
2795 changed.
2796
2797 babel.dates.get_timezone_gmt(datetime=None, width='long', lo‐
2798 cale='en_US_POSIX', return_z=False)
2799 Return the timezone associated with the given datetime object
2800 formatted as string indicating the offset from GMT.
2801
2802 >>> dt = datetime(2007, 4, 1, 15, 30)
2803 >>> get_timezone_gmt(dt, locale='en')
2804 u'GMT+00:00'
2805 >>> get_timezone_gmt(dt, locale='en', return_z=True)
2806 'Z'
2807 >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
2808 u'+00'
2809 >>> tz = get_timezone('America/Los_Angeles')
2810 >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
2811 >>> get_timezone_gmt(dt, locale='en')
2812 u'GMT-07:00'
2813 >>> get_timezone_gmt(dt, 'short', locale='en')
2814 u'-0700'
2815 >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
2816 u'-07'
2817
2818 The long format depends on the locale, for example in France the
2819 acronym UTC string is used instead of GMT:
2820
2821 >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
2822 u'UTC-07:00'
2823
2824 New in version 0.9.
2825
2826
2827 Parameters
2828
2829 • datetime – the datetime object; if None, the current
2830 date and time in UTC is used
2831
2832 • width – either “long” or “short” or “iso8601” or
2833 “iso8601_short”
2834
2835 • locale – the Locale object, or a locale string
2836
2837 • return_z – True or False; Function returns indicator
2838 “Z” when local time offset is 0
2839
2840 babel.dates.get_timezone_location(dt_or_tzinfo=None, lo‐
2841 cale='en_US_POSIX', return_city=False)
2842 Return a representation of the given timezone using “location
2843 format”.
2844
2845 The result depends on both the local display name of the country
2846 and the city associated with the time zone:
2847
2848 >>> tz = get_timezone('America/St_Johns')
2849 >>> print(get_timezone_location(tz, locale='de_DE'))
2850 Kanada (St. John’s) Zeit
2851 >>> print(get_timezone_location(tz, locale='en'))
2852 Canada (St. John’s) Time
2853 >>> print(get_timezone_location(tz, locale='en', return_city=True))
2854 St. John’s
2855 >>> tz = get_timezone('America/Mexico_City')
2856 >>> get_timezone_location(tz, locale='de_DE')
2857 u'Mexiko (Mexiko-Stadt) Zeit'
2858
2859 If the timezone is associated with a country that uses only a
2860 single timezone, just the localized country name is returned:
2861
2862 >>> tz = get_timezone('Europe/Berlin')
2863 >>> get_timezone_name(tz, locale='de_DE')
2864 u'Mitteleurop\xe4ische Zeit'
2865
2866 New in version 0.9.
2867
2868
2869 Parameters
2870
2871 • dt_or_tzinfo – the datetime or tzinfo object that de‐
2872 termines the timezone; if None, the current date and
2873 time in UTC is assumed
2874
2875 • locale – the Locale object, or a locale string
2876
2877 • return_city – True or False, if True then return exem‐
2878 plar city (location) for the time zone
2879
2880 Returns
2881 the localized timezone name using location format
2882
2883 babel.dates.get_timezone_name(dt_or_tzinfo=None, width='long', uncom‐
2884 mon=False, locale='en_US_POSIX', zone_variant=None, return_zone=False)
2885 Return the localized display name for the given timezone. The
2886 timezone may be specified using a datetime or tzinfo object.
2887
2888 >>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
2889 >>> get_timezone_name(dt, locale='en_US')
2890 u'Pacific Standard Time'
2891 >>> get_timezone_name(dt, locale='en_US', return_zone=True)
2892 'America/Los_Angeles'
2893 >>> get_timezone_name(dt, width='short', locale='en_US')
2894 u'PST'
2895
2896 If this function gets passed only a tzinfo object and no con‐
2897 crete datetime, the returned display name is indenpendent of
2898 daylight savings time. This can be used for example for select‐
2899 ing timezones, or to set the time of events that recur across
2900 DST changes:
2901
2902 >>> tz = get_timezone('America/Los_Angeles')
2903 >>> get_timezone_name(tz, locale='en_US')
2904 u'Pacific Time'
2905 >>> get_timezone_name(tz, 'short', locale='en_US')
2906 u'PT'
2907
2908 If no localized display name for the timezone is available, and
2909 the timezone is associated with a country that uses only a sin‐
2910 gle timezone, the name of that country is returned, formatted
2911 according to the locale:
2912
2913 >>> tz = get_timezone('Europe/Berlin')
2914 >>> get_timezone_name(tz, locale='de_DE')
2915 u'Mitteleurop\xe4ische Zeit'
2916 >>> get_timezone_name(tz, locale='pt_BR')
2917 u'Hor\xe1rio da Europa Central'
2918
2919 On the other hand, if the country uses multiple timezones, the
2920 city is also included in the representation:
2921
2922 >>> tz = get_timezone('America/St_Johns')
2923 >>> get_timezone_name(tz, locale='de_DE')
2924 u'Neufundland-Zeit'
2925
2926 Note that short format is currently not supported for all time‐
2927 zones and all locales. This is partially because not every
2928 timezone has a short code in every locale. In that case it cur‐
2929 rently falls back to the long format.
2930
2931 For more information see LDML Appendix J: Time Zone Display
2932 Names
2933
2934 New in version 0.9.
2935
2936
2937 Changed in version 1.0: Added zone_variant support.
2938
2939
2940 Parameters
2941
2942 • dt_or_tzinfo – the datetime or tzinfo object that de‐
2943 termines the timezone; if a tzinfo object is used, the
2944 resulting display name will be generic, i.e. indepen‐
2945 dent of daylight savings time; if None, the current
2946 date in UTC is assumed
2947
2948 • width – either “long” or “short”
2949
2950 • uncommon – deprecated and ignored
2951
2952 • zone_variant – defines the zone variation to return.
2953 By default the variation is defined from the datetime
2954 object passed in. If no datetime object is passed in,
2955 the 'generic' variation is assumed. The following val‐
2956 ues are valid: 'generic', 'daylight' and 'standard'.
2957
2958 • locale – the Locale object, or a locale string
2959
2960 • return_zone – True or False. If true then function re‐
2961 turns long time zone ID
2962
2963 babel.dates.get_next_timezone_transition(zone=None, dt=None)
2964 Given a timezone it will return a TimezoneTransition object that
2965 holds the information about the next timezone transition that’s
2966 going to happen. For instance this can be used to detect when
2967 the next DST change is going to happen and how it looks like.
2968
2969 The transition is calculated relative to the given datetime ob‐
2970 ject. The next transition that follows the date is used. If a
2971 transition cannot be found the return value will be None.
2972
2973 Transition information can only be provided for timezones re‐
2974 turned by the get_timezone() function.
2975
2976 This function is pending deprecation with no replacement planned
2977 in the Babel library.
2978
2979 Parameters
2980
2981 • zone – the timezone for which the transition should be
2982 looked up. If not provided the local timezone is used.
2983
2984 • dt – the date after which the next transition should be
2985 found. If not given the current time is assumed.
2986
2987 babel.dates.UTC
2988 A timezone object for UTC.
2989
2990 babel.dates.LOCALTZ
2991 A timezone object for the computer’s local timezone.
2992
2993 class babel.dates.TimezoneTransition(activates, from_tzinfo, to_tzinfo,
2994 reference_date=None)
2995 A helper object that represents the return value from
2996 get_next_timezone_transition().
2997
2998 This class is pending deprecation with no replacement planned in
2999 the Babel library.
3000
3001 Field activates
3002 The time of the activation of the timezone transition in
3003 UTC.
3004
3005 Field from_tzinfo
3006 The timezone from where the transition starts.
3007
3008 Field to_tzinfo
3009 The timezone for after the transition.
3010
3011 Field reference_date
3012 The reference date that was provided. This is the dt pa‐
3013 rameter to the get_next_timezone_transition().
3014
3015 Data Access
3016 babel.dates.get_period_names(width='wide', context='stand-alone', lo‐
3017 cale='en_US_POSIX')
3018 Return the names for day periods (AM/PM) used by the locale.
3019
3020 >>> get_period_names(locale='en_US')['am']
3021 u'AM'
3022
3023 Parameters
3024
3025 • width – the width to use, one of “abbreviated”, “nar‐
3026 row”, or “wide”
3027
3028 • context – the context, either “format” or “stand-alone”
3029
3030 • locale – the Locale object, or a locale string
3031
3032 babel.dates.get_day_names(width='wide', context='format', lo‐
3033 cale='en_US_POSIX')
3034 Return the day names used by the locale for the specified for‐
3035 mat.
3036
3037 >>> get_day_names('wide', locale='en_US')[1]
3038 u'Tuesday'
3039 >>> get_day_names('short', locale='en_US')[1]
3040 u'Tu'
3041 >>> get_day_names('abbreviated', locale='es')[1]
3042 u'mar'
3043 >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
3044 u'D'
3045
3046 Parameters
3047
3048 • width – the width to use, one of “wide”, “abbreviated”,
3049 “short” or “narrow”
3050
3051 • context – the context, either “format” or “stand-alone”
3052
3053 • locale – the Locale object, or a locale string
3054
3055 babel.dates.get_month_names(width='wide', context='format', lo‐
3056 cale='en_US_POSIX')
3057 Return the month names used by the locale for the specified for‐
3058 mat.
3059
3060 >>> get_month_names('wide', locale='en_US')[1]
3061 u'January'
3062 >>> get_month_names('abbreviated', locale='es')[1]
3063 u'ene'
3064 >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
3065 u'J'
3066
3067 Parameters
3068
3069 • width – the width to use, one of “wide”, “abbreviated”,
3070 or “narrow”
3071
3072 • context – the context, either “format” or “stand-alone”
3073
3074 • locale – the Locale object, or a locale string
3075
3076 babel.dates.get_quarter_names(width='wide', context='format', lo‐
3077 cale='en_US_POSIX')
3078 Return the quarter names used by the locale for the specified
3079 format.
3080
3081 >>> get_quarter_names('wide', locale='en_US')[1]
3082 u'1st quarter'
3083 >>> get_quarter_names('abbreviated', locale='de_DE')[1]
3084 u'Q1'
3085 >>> get_quarter_names('narrow', locale='de_DE')[1]
3086 u'1'
3087
3088 Parameters
3089
3090 • width – the width to use, one of “wide”, “abbreviated”,
3091 or “narrow”
3092
3093 • context – the context, either “format” or “stand-alone”
3094
3095 • locale – the Locale object, or a locale string
3096
3097 babel.dates.get_era_names(width='wide', locale='en_US_POSIX')
3098 Return the era names used by the locale for the specified for‐
3099 mat.
3100
3101 >>> get_era_names('wide', locale='en_US')[1]
3102 u'Anno Domini'
3103 >>> get_era_names('abbreviated', locale='de_DE')[1]
3104 u'n. Chr.'
3105
3106 Parameters
3107
3108 • width – the width to use, either “wide”, “abbreviated”,
3109 or “narrow”
3110
3111 • locale – the Locale object, or a locale string
3112
3113 babel.dates.get_date_format(format='medium', locale='en_US_POSIX')
3114 Return the date formatting patterns used by the locale for the
3115 specified format.
3116
3117 >>> get_date_format(locale='en_US')
3118 <DateTimePattern u'MMM d, y'>
3119 >>> get_date_format('full', locale='de_DE')
3120 <DateTimePattern u'EEEE, d. MMMM y'>
3121
3122 Parameters
3123
3124 • format – the format to use, one of “full”, “long”,
3125 “medium”, or “short”
3126
3127 • locale – the Locale object, or a locale string
3128
3129 babel.dates.get_datetime_format(format='medium', locale='en_US_POSIX')
3130 Return the datetime formatting patterns used by the locale for
3131 the specified format.
3132
3133 >>> get_datetime_format(locale='en_US')
3134 u'{1}, {0}'
3135
3136 Parameters
3137
3138 • format – the format to use, one of “full”, “long”,
3139 “medium”, or “short”
3140
3141 • locale – the Locale object, or a locale string
3142
3143 babel.dates.get_time_format(format='medium', locale='en_US_POSIX')
3144 Return the time formatting patterns used by the locale for the
3145 specified format.
3146
3147 >>> get_time_format(locale='en_US')
3148 <DateTimePattern u'h:mm:ss a'>
3149 >>> get_time_format('full', locale='de_DE')
3150 <DateTimePattern u'HH:mm:ss zzzz'>
3151
3152 Parameters
3153
3154 • format – the format to use, one of “full”, “long”,
3155 “medium”, or “short”
3156
3157 • locale – the Locale object, or a locale string
3158
3159 Basic Parsing
3160 babel.dates.parse_date(string, locale='en_US_POSIX', format='medium')
3161 Parse a date from a string.
3162
3163 This function first tries to interpret the string as ISO-8601
3164 date format, then uses the date format for the locale as a hint
3165 to determine the order in which the date fields appear in the
3166 string.
3167
3168 >>> parse_date('4/1/04', locale='en_US')
3169 datetime.date(2004, 4, 1)
3170 >>> parse_date('01.04.2004', locale='de_DE')
3171 datetime.date(2004, 4, 1)
3172 >>> parse_date('2004-04-01', locale='en_US')
3173 datetime.date(2004, 4, 1)
3174 >>> parse_date('2004-04-01', locale='de_DE')
3175 datetime.date(2004, 4, 1)
3176
3177 Parameters
3178
3179 • string – the string containing the date
3180
3181 • locale – a Locale object or a locale identifier
3182
3183 • format – the format to use (see get_date_format)
3184
3185 babel.dates.parse_time(string, locale='en_US_POSIX', format='medium')
3186 Parse a time from a string.
3187
3188 This function uses the time format for the locale as a hint to
3189 determine the order in which the time fields appear in the
3190 string.
3191
3192 >>> parse_time('15:30:00', locale='en_US')
3193 datetime.time(15, 30)
3194
3195 Parameters
3196
3197 • string – the string containing the time
3198
3199 • locale – a Locale object or a locale identifier
3200
3201 • format – the format to use (see get_time_format)
3202
3203 Returns
3204 the parsed time
3205
3206 Return type
3207 time
3208
3209 babel.dates.parse_pattern(pattern)
3210 Parse date, time, and datetime format patterns.
3211
3212 >>> parse_pattern("MMMMd").format
3213 u'%(MMMM)s%(d)s'
3214 >>> parse_pattern("MMM d, yyyy").format
3215 u'%(MMM)s %(d)s, %(yyyy)s'
3216
3217 Pattern can contain literal strings in single quotes:
3218
3219 >>> parse_pattern("H:mm' Uhr 'z").format
3220 u'%(H)s:%(mm)s Uhr %(z)s'
3221
3222 An actual single quote can be used by using two adjacent single
3223 quote characters:
3224
3225 >>> parse_pattern("hh' o''clock'").format
3226 u"%(hh)s o'clock"
3227
3228 Parameters
3229 pattern – the formatting pattern to parse
3230
3231 Languages
3232 The languages module provides functionality to access data about lan‐
3233 guages that is not bound to a given locale.
3234
3235 Official Languages
3236 babel.languages.get_official_languages(territory, regional=False,
3237 de_facto=False)
3238 Get the official language(s) for the given territory.
3239
3240 The language codes, if any are known, are returned in order of
3241 descending popularity.
3242
3243 If the regional flag is set, then languages which are regionally
3244 official are also returned.
3245
3246 If the de_facto flag is set, then languages which are “de facto”
3247 official are also returned.
3248
3249 WARNING:
3250 Note that the data is as up to date as the current version of
3251 the CLDR used by Babel. If you need scientifically accurate
3252 information, use another source!
3253
3254 Parameters
3255
3256 • territory (str) – Territory code
3257
3258 • regional (bool) – Whether to return regionally official
3259 languages too
3260
3261 • de_facto (bool) – Whether to return de-facto official
3262 languages too
3263
3264 Returns
3265 Tuple of language codes
3266
3267 Return type
3268 tuple[str]
3269
3270 babel.languages.get_territory_language_info(territory)
3271 Get a dictionary of language information for a territory.
3272
3273 The dictionary is keyed by language code; the values are dicts
3274 with more information.
3275
3276 The following keys are currently known for the values:
3277
3278 •
3279
3280 population_percent: The percentage of the territory’s popula‐
3281 tion speaking the
3282 language.
3283
3284 •
3285
3286 official_status: An optional string describing the officiality
3287 status of the language.
3288 Known values are “official”, “official_regional” and
3289 “de_facto_official”.
3290
3291 WARNING:
3292 Note that the data is as up to date as the current version of
3293 the CLDR used by Babel. If you need scientifically accurate
3294 information, use another source!
3295
3296 NOTE:
3297 Note that the format of the dict returned may change between
3298 Babel versions.
3299
3300 See
3301 https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
3302
3303 Parameters
3304 territory (str) – Territory code
3305
3306 Returns
3307 Language information dictionary
3308
3309 Return type
3310 dict[str, dict]
3311
3312 List Formatting
3313 This module lets you format lists of items in a locale-dependent man‐
3314 ner.
3315
3316 babel.lists.format_list(lst, style='standard', locale='en_US_POSIX')
3317 Format the items in lst as a list.
3318
3319 >>> format_list(['apples', 'oranges', 'pears'], locale='en')
3320 u'apples, oranges, and pears'
3321 >>> format_list(['apples', 'oranges', 'pears'], locale='zh')
3322 u'apples、oranges和pears'
3323 >>> format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
3324 u'omena, peruna tai aplari'
3325
3326 These styles are defined, but not all are necessarily available
3327 in all locales. The following text is verbatim from the Unicode
3328 TR35-49 spec [1].
3329
3330 • standard: A typical ‘and’ list for arbitrary placeholders.
3331 eg. “January, February, and March”
3332
3333 • standard-short: A short version of a ‘and’ list, suitable for
3334 use with short or abbreviated placeholder values. eg. “Jan.,
3335 Feb., and Mar.”
3336
3337 • or: A typical ‘or’ list for arbitrary placeholders. eg. “Jan‐
3338 uary, February, or March”
3339
3340 • or-short: A short version of an ‘or’ list. eg. “Jan., Feb.,
3341 or Mar.”
3342
3343 • unit: A list suitable for wide units. eg. “3 feet, 7 inches”
3344
3345 • unit-short: A list suitable for short units eg. “3 ft, 7 in”
3346
3347 • unit-narrow: A list suitable for narrow units, where space on
3348 the screen is very limited. eg. “3′ 7″”
3349
3350 [1]:
3351 https://www.unicode.org/reports/tr35/tr35-49/tr35-general.html#ListPatterns
3352
3353 Parameters
3354
3355 • lst – a sequence of items to format in to a list
3356
3357 • style – the style to format the list with. See above
3358 for description.
3359
3360 • locale – the locale
3361
3362 Messages and Catalogs
3363 Babel provides functionality to work with message catalogs. This part
3364 of the API documentation shows those parts.
3365
3366 Messages and Catalogs
3367 This module provides a basic interface to hold catalog and message in‐
3368 formation. It’s generally used to modify a gettext catalog but it is
3369 not being used to actually use the translations.
3370
3371 Catalogs
3372 class babel.messages.catalog.Catalog(locale=None, domain=None,
3373 header_comment='# Translations template for PROJECT.\n# Copyright (C)
3374 YEAR ORGANIZATION\n# This file is distributed under the same license as
3375 the PROJECT project.\n# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n#',
3376 project=None, version=None, copyright_holder=None, msgid_bugs_ad‐
3377 dress=None, creation_date=None, revision_date=None, last_transla‐
3378 tor=None, language_team=None, charset=None, fuzzy=True)
3379 Representation of a message catalog.
3380
3381 __iter__()
3382 Iterates through all the entries in the catalog, in the
3383 order they were added, yielding a Message object for ev‐
3384 ery entry.
3385
3386 Return type
3387 iterator
3388
3389 add(id, string=None, locations=(), flags=(), auto_comments=(),
3390 user_comments=(), previous_id=(), lineno=None, context=None)
3391 Add or update the message with the specified ID.
3392
3393 >>> catalog = Catalog()
3394 >>> catalog.add(u'foo')
3395 <Message ...>
3396 >>> catalog[u'foo']
3397 <Message u'foo' (flags: [])>
3398
3399 This method simply constructs a Message object with the
3400 given arguments and invokes __setitem__ with that object.
3401
3402 Parameters
3403
3404 • id – the message ID, or a (singular, plural) tu‐
3405 ple for pluralizable messages
3406
3407 • string – the translated message string, or a
3408 (singular, plural) tuple for pluralizable mes‐
3409 sages
3410
3411 • locations – a sequence of (filename, lineno) tu‐
3412 ples
3413
3414 • flags – a set or sequence of flags
3415
3416 • auto_comments – a sequence of automatic comments
3417
3418 • user_comments – a sequence of user comments
3419
3420 • previous_id – the previous message ID, or a
3421 (singular, plural) tuple for pluralizable mes‐
3422 sages
3423
3424 • lineno – the line number on which the msgid line
3425 was found in the PO file, if any
3426
3427 • context – the message context
3428
3429 check()
3430 Run various validation checks on the translations in the
3431 catalog.
3432
3433 For every message which fails validation, this method
3434 yield a (message, errors) tuple, where message is the
3435 Message object and errors is a sequence of Translation‐
3436 Error objects.
3437
3438 Return type
3439 iterator
3440
3441 delete(id, context=None)
3442 Delete the message with the specified ID and context.
3443
3444 Parameters
3445
3446 • id – the message ID
3447
3448 • context – the message context, or None for no
3449 context
3450
3451 get(id, context=None)
3452 Return the message with the specified ID and context.
3453
3454 Parameters
3455
3456 • id – the message ID
3457
3458 • context – the message context, or None for no
3459 context
3460
3461 property header_comment
3462 The header comment for the catalog.
3463
3464 >>> catalog = Catalog(project='Foobar', version='1.0',
3465 ... copyright_holder='Foo Company')
3466 >>> print(catalog.header_comment)
3467 # Translations template for Foobar.
3468 # Copyright (C) ... Foo Company
3469 # This file is distributed under the same license as the Foobar project.
3470 # FIRST AUTHOR <EMAIL@ADDRESS>, ....
3471 #
3472
3473 The header can also be set from a string. Any known up‐
3474 per-case variables will be replaced when the header is
3475 retrieved again:
3476
3477 >>> catalog = Catalog(project='Foobar', version='1.0',
3478 ... copyright_holder='Foo Company')
3479 >>> catalog.header_comment = '''\
3480 ... # The POT for my really cool PROJECT project.
3481 ... # Copyright (C) 1990-2003 ORGANIZATION
3482 ... # This file is distributed under the same license as the PROJECT
3483 ... # project.
3484 ... #'''
3485 >>> print(catalog.header_comment)
3486 # The POT for my really cool Foobar project.
3487 # Copyright (C) 1990-2003 Foo Company
3488 # This file is distributed under the same license as the Foobar
3489 # project.
3490 #
3491
3492 Type unicode
3493
3494 is_identical(other)
3495 Checks if catalogs are identical, taking into account
3496 messages and headers.
3497
3498 language_team
3499 Name and email address of the language team.
3500
3501 last_translator
3502 Name and email address of the last translator.
3503
3504 property mime_headers
3505 The MIME headers of the catalog, used for the special ms‐
3506 gid "" entry.
3507
3508 The behavior of this property changes slightly depending
3509 on whether a locale is set or not, the latter indicating
3510 that the catalog is actually a template for actual trans‐
3511 lations.
3512
3513 Here’s an example of the output for such a catalog tem‐
3514 plate:
3515
3516 >>> from babel.dates import UTC
3517 >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
3518 >>> catalog = Catalog(project='Foobar', version='1.0',
3519 ... creation_date=created)
3520 >>> for name, value in catalog.mime_headers:
3521 ... print('%s: %s' % (name, value))
3522 Project-Id-Version: Foobar 1.0
3523 Report-Msgid-Bugs-To: EMAIL@ADDRESS
3524 POT-Creation-Date: 1990-04-01 15:30+0000
3525 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
3526 Last-Translator: FULL NAME <EMAIL@ADDRESS>
3527 Language-Team: LANGUAGE <LL@li.org>
3528 MIME-Version: 1.0
3529 Content-Type: text/plain; charset=utf-8
3530 Content-Transfer-Encoding: 8bit
3531 Generated-By: Babel ...
3532
3533 And here’s an example of the output when the locale is
3534 set:
3535
3536 >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
3537 >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
3538 ... creation_date=created, revision_date=revised,
3539 ... last_translator='John Doe <jd@example.com>',
3540 ... language_team='de_DE <de@example.com>')
3541 >>> for name, value in catalog.mime_headers:
3542 ... print('%s: %s' % (name, value))
3543 Project-Id-Version: Foobar 1.0
3544 Report-Msgid-Bugs-To: EMAIL@ADDRESS
3545 POT-Creation-Date: 1990-04-01 15:30+0000
3546 PO-Revision-Date: 1990-08-03 12:00+0000
3547 Last-Translator: John Doe <jd@example.com>
3548 Language: de_DE
3549 Language-Team: de_DE <de@example.com>
3550 Plural-Forms: nplurals=2; plural=(n != 1);
3551 MIME-Version: 1.0
3552 Content-Type: text/plain; charset=utf-8
3553 Content-Transfer-Encoding: 8bit
3554 Generated-By: Babel ...
3555
3556 Type list
3557
3558 property num_plurals
3559 The number of plurals used by the catalog or locale.
3560
3561 >>> Catalog(locale='en').num_plurals
3562 2
3563 >>> Catalog(locale='ga').num_plurals
3564 5
3565
3566 Type int
3567
3568 property plural_expr
3569 The plural expression used by the catalog or locale.
3570
3571 >>> Catalog(locale='en').plural_expr
3572 '(n != 1)'
3573 >>> Catalog(locale='ga').plural_expr
3574 '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)'
3575 >>> Catalog(locale='ding').plural_expr # unknown locale
3576 '(n != 1)'
3577
3578 Type str
3579
3580 property plural_forms
3581 Return the plural forms declaration for the locale.
3582
3583 >>> Catalog(locale='en').plural_forms
3584 'nplurals=2; plural=(n != 1);'
3585 >>> Catalog(locale='pt_BR').plural_forms
3586 'nplurals=2; plural=(n > 1);'
3587
3588 Type str
3589
3590 update(template, no_fuzzy_matching=False, update_header_com‐
3591 ment=False, keep_user_comments=True)
3592 Update the catalog based on the given template catalog.
3593
3594 >>> from babel.messages import Catalog
3595 >>> template = Catalog()
3596 >>> template.add('green', locations=[('main.py', 99)])
3597 <Message ...>
3598 >>> template.add('blue', locations=[('main.py', 100)])
3599 <Message ...>
3600 >>> template.add(('salad', 'salads'), locations=[('util.py', 42)])
3601 <Message ...>
3602 >>> catalog = Catalog(locale='de_DE')
3603 >>> catalog.add('blue', u'blau', locations=[('main.py', 98)])
3604 <Message ...>
3605 >>> catalog.add('head', u'Kopf', locations=[('util.py', 33)])
3606 <Message ...>
3607 >>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'),
3608 ... locations=[('util.py', 38)])
3609 <Message ...>
3610
3611 >>> catalog.update(template)
3612 >>> len(catalog)
3613 3
3614
3615 >>> msg1 = catalog['green']
3616 >>> msg1.string
3617 >>> msg1.locations
3618 [('main.py', 99)]
3619
3620 >>> msg2 = catalog['blue']
3621 >>> msg2.string
3622 u'blau'
3623 >>> msg2.locations
3624 [('main.py', 100)]
3625
3626 >>> msg3 = catalog['salad']
3627 >>> msg3.string
3628 (u'Salat', u'Salate')
3629 >>> msg3.locations
3630 [('util.py', 42)]
3631
3632 Messages that are in the catalog but not in the template
3633 are removed from the main collection, but can still be
3634 accessed via the obsolete member:
3635
3636 >>> 'head' in catalog
3637 False
3638 >>> list(catalog.obsolete.values())
3639 [<Message 'head' (flags: [])>]
3640
3641 Parameters
3642
3643 • template – the reference catalog, usually read
3644 from a POT file
3645
3646 • no_fuzzy_matching – whether to use fuzzy match‐
3647 ing of message IDs
3648
3649 Messages
3650 class babel.messages.catalog.Message(id, string='', locations=(),
3651 flags=(), auto_comments=(), user_comments=(), previous_id=(),
3652 lineno=None, context=None)
3653 Representation of a single message in a catalog.
3654
3655 check(catalog=None)
3656 Run various validation checks on the message. Some vali‐
3657 dations are only performed if the catalog is provided.
3658 This method returns a sequence of TranslationError ob‐
3659 jects.
3660
3661 Return type
3662 iterator
3663
3664 Parameters
3665 catalog – A catalog instance that is passed to the
3666 checkers
3667
3668 See Catalog.check for a way to perform checks for all
3669 messages in a catalog.
3670
3671 property fuzzy
3672 Whether the translation is fuzzy.
3673
3674 >>> Message('foo').fuzzy
3675 False
3676 >>> msg = Message('foo', 'foo', flags=['fuzzy'])
3677 >>> msg.fuzzy
3678 True
3679 >>> msg
3680 <Message 'foo' (flags: ['fuzzy'])>
3681
3682 Type bool
3683
3684 is_identical(other)
3685 Checks whether messages are identical, taking into ac‐
3686 count all properties.
3687
3688 property pluralizable
3689 Whether the message is plurizable.
3690
3691 >>> Message('foo').pluralizable
3692 False
3693 >>> Message(('foo', 'bar')).pluralizable
3694 True
3695
3696 Type bool
3697
3698 property python_format
3699 Whether the message contains Python-style parameters.
3700
3701 >>> Message('foo %(name)s bar').python_format
3702 True
3703 >>> Message(('foo %(name)s', 'foo %(name)s')).python_format
3704 True
3705
3706 Type bool
3707
3708 Exceptions
3709 exception babel.messages.catalog.TranslationError
3710 Exception thrown by translation checkers when invalid message
3711 translations are encountered.
3712
3713 Low-Level Extraction Interface
3714 The low level extraction interface can be used to extract from directo‐
3715 ries or files directly. Normally this is not needed as the command
3716 line tools can do that for you.
3717
3718 Extraction Functions
3719 The extraction functions are what the command line tools use internally
3720 to extract strings.
3721
3722 babel.messages.extract.extract_from_dir(dirname=None,
3723 method_map=[('**.py', 'python')], options_map=None, keywords={'N_':
3724 None, '_': None, 'dgettext': (2,), 'dngettext': (2, 3), 'gettext':
3725 None, 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3), 'pgettext':
3726 ((1, 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, comment_tags=(),
3727 callback=None, strip_comment_tags=False, directory_filter=None)
3728 Extract messages from any source files found in the given direc‐
3729 tory.
3730
3731 This function generates tuples of the form (filename, lineno,
3732 message, comments, context).
3733
3734 Which extraction method is used per file is determined by the
3735 method_map parameter, which maps extended glob patterns to ex‐
3736 traction method names. For example, the following is the de‐
3737 fault mapping:
3738
3739 >>> method_map = [
3740 ... ('**.py', 'python')
3741 ... ]
3742
3743 This basically says that files with the filename extension “.py”
3744 at any level inside the directory should be processed by the
3745 “python” extraction method. Files that don’t match any of the
3746 mapping patterns are ignored. See the documentation of the path‐
3747 match function for details on the pattern syntax.
3748
3749 The following extended mapping would also use the “genshi” ex‐
3750 traction method on any file in “templates” subdirectory:
3751
3752 >>> method_map = [
3753 ... ('**/templates/**.*', 'genshi'),
3754 ... ('**.py', 'python')
3755 ... ]
3756
3757 The dictionary provided by the optional options_map parameter
3758 augments these mappings. It uses extended glob patterns as keys,
3759 and the values are dictionaries mapping options names to option
3760 values (both strings).
3761
3762 The glob patterns of the options_map do not necessarily need to
3763 be the same as those used in the method mapping. For example,
3764 while all files in the templates folders in an application may
3765 be Genshi applications, the options for those files may differ
3766 based on extension:
3767
3768 >>> options_map = {
3769 ... '**/templates/**.txt': {
3770 ... 'template_class': 'genshi.template:TextTemplate',
3771 ... 'encoding': 'latin-1'
3772 ... },
3773 ... '**/templates/**.html': {
3774 ... 'include_attrs': ''
3775 ... }
3776 ... }
3777
3778 Parameters
3779
3780 • dirname – the path to the directory to extract messages
3781 from. If not given the current working directory is
3782 used.
3783
3784 • method_map – a list of (pattern, method) tuples that
3785 maps of extraction method names to extended glob pat‐
3786 terns
3787
3788 • options_map – a dictionary of additional options (op‐
3789 tional)
3790
3791 • keywords – a dictionary mapping keywords (i.e. names of
3792 functions that should be recognized as translation
3793 functions) to tuples that specify which of their argu‐
3794 ments contain localizable strings
3795
3796 • comment_tags – a list of tags of translator comments to
3797 search for and include in the results
3798
3799 • callback – a function that is called for every file
3800 that message are extracted from, just before the ex‐
3801 traction itself is performed; the function is passed
3802 the filename, the name of the extraction method and and
3803 the options dictionary as positional arguments, in that
3804 order
3805
3806 • strip_comment_tags – a flag that if set to True causes
3807 all comment tags to be removed from the collected com‐
3808 ments.
3809
3810 • directory_filter – a callback to determine whether a
3811 directory should be recursed into. Receives the full
3812 directory path; should return True if the directory is
3813 valid.
3814
3815 See pathmatch
3816
3817 babel.messages.extract.extract_from_file(method, filename, key‐
3818 words={'N_': None, '_': None, 'dgettext': (2,), 'dngettext': (2, 3),
3819 'gettext': None, 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3),
3820 'pgettext': ((1, 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, com‐
3821 ment_tags=(), options=None, strip_comment_tags=False)
3822 Extract messages from a specific file.
3823
3824 This function returns a list of tuples of the form (lineno, mes‐
3825 sage, comments, context).
3826
3827 Parameters
3828
3829 • filename – the path to the file to extract messages
3830 from
3831
3832 • method – a string specifying the extraction method
3833 (.e.g. “python”)
3834
3835 • keywords – a dictionary mapping keywords (i.e. names of
3836 functions that should be recognized as translation
3837 functions) to tuples that specify which of their argu‐
3838 ments contain localizable strings
3839
3840 • comment_tags – a list of translator tags to search for
3841 and include in the results
3842
3843 • strip_comment_tags – a flag that if set to True causes
3844 all comment tags to be removed from the collected com‐
3845 ments.
3846
3847 • options – a dictionary of additional options (optional)
3848
3849 Returns
3850 list of tuples of the form (lineno, message, comments,
3851 context)
3852
3853 Return type
3854 list[tuple[int, str|tuple[str], list[str], str|None]
3855
3856 babel.messages.extract.extract(method, fileobj, keywords={'N_': None,
3857 '_': None, 'dgettext': (2,), 'dngettext': (2, 3), 'gettext': None,
3858 'ngettext': (1, 2), 'npgettext': ((1, 'c'), 2, 3), 'pgettext': ((1,
3859 'c'), 2), 'ugettext': None, 'ungettext': (1, 2)}, comment_tags=(), op‐
3860 tions=None, strip_comment_tags=False)
3861 Extract messages from the given file-like object using the spec‐
3862 ified extraction method.
3863
3864 This function returns tuples of the form (lineno, message, com‐
3865 ments, context).
3866
3867 The implementation dispatches the actual extraction to plugins,
3868 based on the value of the method parameter.
3869
3870 >>> source = b'''# foo module
3871 ... def run(argv):
3872 ... print(_('Hello, world!'))
3873 ... '''
3874
3875 >>> from io import BytesIO
3876 >>> for message in extract('python', BytesIO(source)):
3877 ... print(message)
3878 (3, u'Hello, world!', [], None)
3879
3880 Parameters
3881
3882 • method – an extraction method (a callable), or a string
3883 specifying the extraction method (.e.g. “python”); if
3884 this is a simple name, the extraction function will be
3885 looked up by entry point; if it is an explicit refer‐
3886 ence to a function (of the form package.module:funcname
3887 or package.module.funcname), the corresponding function
3888 will be imported and used
3889
3890 • fileobj – the file-like object the messages should be
3891 extracted from
3892
3893 • keywords – a dictionary mapping keywords (i.e. names of
3894 functions that should be recognized as translation
3895 functions) to tuples that specify which of their argu‐
3896 ments contain localizable strings
3897
3898 • comment_tags – a list of translator tags to search for
3899 and include in the results
3900
3901 • options – a dictionary of additional options (optional)
3902
3903 • strip_comment_tags – a flag that if set to True causes
3904 all comment tags to be removed from the collected com‐
3905 ments.
3906
3907 Raises ValueError – if the extraction method is not registered
3908
3909 Returns
3910 iterable of tuples of the form (lineno, message, com‐
3911 ments, context)
3912
3913 Return type
3914 Iterable[tuple[int, str|tuple[str], list[str], str|None]
3915
3916 Language Parsing
3917 The language parsing functions are used to extract strings out of
3918 source files. These are automatically being used by the extraction
3919 functions but sometimes it can be useful to register wrapper functions,
3920 then these low level functions can be invoked.
3921
3922 New functions can be registered through the setuptools entrypoint sys‐
3923 tem.
3924
3925 babel.messages.extract.extract_python(fileobj, keywords, comment_tags,
3926 options)
3927 Extract messages from Python source code.
3928
3929 It returns an iterator yielding tuples in the following form
3930 (lineno, funcname, message, comments).
3931
3932 Parameters
3933
3934 • fileobj – the seekable, file-like object the messages
3935 should be extracted from
3936
3937 • keywords – a list of keywords (i.e. function names)
3938 that should be recognized as translation functions
3939
3940 • comment_tags – a list of translator tags to search for
3941 and include in the results
3942
3943 • options – a dictionary of additional options (optional)
3944
3945 Return type
3946 iterator
3947
3948 babel.messages.extract.extract_javascript(fileobj, keywords, com‐
3949 ment_tags, options)
3950 Extract messages from JavaScript source code.
3951
3952 Parameters
3953
3954 • fileobj – the seekable, file-like object the messages
3955 should be extracted from
3956
3957 • keywords – a list of keywords (i.e. function names)
3958 that should be recognized as translation functions
3959
3960 • comment_tags – a list of translator tags to search for
3961 and include in the results
3962
3963 • options – a dictionary of additional options (optional)
3964 Supported options are: * jsx – set to false to disable
3965 JSX/E4X support. * template_string – set to false to
3966 disable ES6 template string support.
3967
3968 babel.messages.extract.extract_nothing(fileobj, keywords, comment_tags,
3969 options)
3970 Pseudo extractor that does not actually extract anything, but
3971 simply returns an empty list.
3972
3973 MO File Support
3974 The MO file support can read and write MO files. It reads them into
3975 Catalog objects and also writes catalogs out.
3976
3977 babel.messages.mofile.read_mo(fileobj)
3978 Read a binary MO file from the given file-like object and return
3979 a corresponding Catalog object.
3980
3981 Parameters
3982 fileobj – the file-like object to read the MO file from
3983
3984 Note The implementation of this function is heavily based on
3985 the GNUTranslations._parse method of the gettext module
3986 in the standard library.
3987
3988 babel.messages.mofile.write_mo(fileobj, catalog, use_fuzzy=False)
3989 Write a catalog to the specified file-like object using the GNU
3990 MO file format.
3991
3992 >>> import sys
3993 >>> from babel.messages import Catalog
3994 >>> from gettext import GNUTranslations
3995 >>> from io import BytesIO
3996
3997 >>> catalog = Catalog(locale='en_US')
3998 >>> catalog.add('foo', 'Voh')
3999 <Message ...>
4000 >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
4001 <Message ...>
4002 >>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
4003 <Message ...>
4004 >>> catalog.add('Fizz', '')
4005 <Message ...>
4006 >>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
4007 <Message ...>
4008 >>> buf = BytesIO()
4009
4010 >>> write_mo(buf, catalog)
4011 >>> x = buf.seek(0)
4012 >>> translations = GNUTranslations(fp=buf)
4013 >>> if sys.version_info[0] >= 3:
4014 ... translations.ugettext = translations.gettext
4015 ... translations.ungettext = translations.ngettext
4016 >>> translations.ugettext('foo')
4017 u'Voh'
4018 >>> translations.ungettext('bar', 'baz', 1)
4019 u'Bahr'
4020 >>> translations.ungettext('bar', 'baz', 2)
4021 u'Batz'
4022 >>> translations.ugettext('fuz')
4023 u'fuz'
4024 >>> translations.ugettext('Fizz')
4025 u'Fizz'
4026 >>> translations.ugettext('Fuzz')
4027 u'Fuzz'
4028 >>> translations.ugettext('Fuzzes')
4029 u'Fuzzes'
4030
4031 Parameters
4032
4033 • fileobj – the file-like object to write to
4034
4035 • catalog – the Catalog instance
4036
4037 • use_fuzzy – whether translations marked as “fuzzy”
4038 should be included in the output
4039
4040 PO File Support
4041 The PO file support can read and write PO and POT files. It reads them
4042 into Catalog objects and also writes catalogs out.
4043
4044 babel.messages.pofile.read_po(fileobj, locale=None, domain=None, ig‐
4045 nore_obsolete=False, charset=None, abort_invalid=False)
4046 Read messages from a gettext PO (portable object) file from the
4047 given file-like object and return a Catalog.
4048
4049 >>> from datetime import datetime
4050 >>> from io import StringIO
4051 >>> buf = StringIO('''
4052 ... #: main.py:1
4053 ... #, fuzzy, python-format
4054 ... msgid "foo %(name)s"
4055 ... msgstr "quux %(name)s"
4056 ...
4057 ... # A user comment
4058 ... #. An auto comment
4059 ... #: main.py:3
4060 ... msgid "bar"
4061 ... msgid_plural "baz"
4062 ... msgstr[0] "bar"
4063 ... msgstr[1] "baaz"
4064 ... ''')
4065 >>> catalog = read_po(buf)
4066 >>> catalog.revision_date = datetime(2007, 4, 1)
4067
4068 >>> for message in catalog:
4069 ... if message.id:
4070 ... print((message.id, message.string))
4071 ... print(' ', (message.locations, sorted(list(message.flags))))
4072 ... print(' ', (message.user_comments, message.auto_comments))
4073 (u'foo %(name)s', u'quux %(name)s')
4074 ([(u'main.py', 1)], [u'fuzzy', u'python-format'])
4075 ([], [])
4076 ((u'bar', u'baz'), (u'bar', u'baaz'))
4077 ([(u'main.py', 3)], [])
4078 ([u'A user comment'], [u'An auto comment'])
4079
4080 New in version 1.0: Added support for explicit charset argument.
4081
4082
4083 Parameters
4084
4085 • fileobj – the file-like object to read the PO file from
4086
4087 • locale – the locale identifier or Locale object, or
4088 None if the catalog is not bound to a locale (which ba‐
4089 sically means it’s a template)
4090
4091 • domain – the message domain
4092
4093 • ignore_obsolete – whether to ignore obsolete messages
4094 in the input
4095
4096 • charset – the character set of the catalog.
4097
4098 • abort_invalid – abort read if po file is invalid
4099
4100 babel.messages.pofile.write_po(fileobj, catalog, width=76, no_loca‐
4101 tion=False, omit_header=False, sort_output=False, sort_by_file=False,
4102 ignore_obsolete=False, include_previous=False, include_lineno=True)
4103 Write a gettext PO (portable object) template file for a given
4104 message catalog to the provided file-like object.
4105
4106 >>> catalog = Catalog()
4107 >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)],
4108 ... flags=('fuzzy',))
4109 <Message...>
4110 >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)])
4111 <Message...>
4112 >>> from io import BytesIO
4113 >>> buf = BytesIO()
4114 >>> write_po(buf, catalog, omit_header=True)
4115 >>> print(buf.getvalue().decode("utf8"))
4116 #: main.py:1
4117 #, fuzzy, python-format
4118 msgid "foo %(name)s"
4119 msgstr ""
4120
4121 #: main.py:3
4122 msgid "bar"
4123 msgid_plural "baz"
4124 msgstr[0] ""
4125 msgstr[1] ""
4126
4127
4128
4129 Parameters
4130
4131 • fileobj – the file-like object to write to
4132
4133 • catalog – the Catalog instance
4134
4135 • width – the maximum line width for the generated out‐
4136 put; use None, 0, or a negative number to completely
4137 disable line wrapping
4138
4139 • no_location – do not emit a location comment for every
4140 message
4141
4142 • omit_header – do not include the msgid "" entry at the
4143 top of the output
4144
4145 • sort_output – whether to sort the messages in the out‐
4146 put by msgid
4147
4148 • sort_by_file – whether to sort the messages in the out‐
4149 put by their locations
4150
4151 • ignore_obsolete – whether to ignore obsolete messages
4152 and not include them in the output; by default they are
4153 included as comments
4154
4155 • include_previous – include the old msgid as a comment
4156 when updating the catalog
4157
4158 • include_lineno – include line number in the location
4159 comment
4160
4161 Numbers and Currencies
4162 The number module provides functionality to format numbers for differ‐
4163 ent locales. This includes arbitrary numbers as well as currency.
4164
4165 Number Formatting
4166 babel.numbers.format_number(number, locale='en_US_POSIX')
4167 Return the given number formatted for a specific locale.
4168
4169 >>> format_number(1099, locale='en_US')
4170 u'1,099'
4171 >>> format_number(1099, locale='de_DE')
4172 u'1.099'
4173
4174 Deprecated since version 2.6.0: Use babel.numbers.format_deci‐
4175 mal() instead.
4176
4177
4178 Parameters
4179
4180 • number – the number to format
4181
4182 • locale – the Locale object or locale identifier
4183
4184 babel.numbers.format_decimal(number, format=None, locale='en_US_POSIX',
4185 decimal_quantization=True, group_separator=True)
4186 Return the given decimal number formatted for a specific locale.
4187
4188 >>> format_decimal(1.2345, locale='en_US')
4189 u'1.234'
4190 >>> format_decimal(1.2346, locale='en_US')
4191 u'1.235'
4192 >>> format_decimal(-1.2346, locale='en_US')
4193 u'-1.235'
4194 >>> format_decimal(1.2345, locale='sv_SE')
4195 u'1,234'
4196 >>> format_decimal(1.2345, locale='de')
4197 u'1,234'
4198
4199 The appropriate thousands grouping and the decimal separator are
4200 used for each locale:
4201
4202 >>> format_decimal(12345.5, locale='en_US')
4203 u'12,345.5'
4204
4205 By default the locale is allowed to truncate and round a
4206 high-precision number by forcing its format pattern onto the
4207 decimal part. You can bypass this behavior with the deci‐
4208 mal_quantization parameter:
4209
4210 >>> format_decimal(1.2346, locale='en_US')
4211 u'1.235'
4212 >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
4213 u'1.2346'
4214 >>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
4215 u'12345,67'
4216 >>> format_decimal(12345.67, locale='en_US', group_separator=True)
4217 u'12,345.67'
4218
4219 Parameters
4220
4221 • number – the number to format
4222
4223 • format –
4224
4225 • locale – the Locale object or locale identifier
4226
4227 • decimal_quantization – Truncate and round high-preci‐
4228 sion numbers to the format pattern. Defaults to True.
4229
4230 • group_separator – Boolean to switch group separator
4231 on/off in a locale’s number format.
4232
4233 babel.numbers.format_compact_decimal(number, *, format_type='short',
4234 locale='en_US_POSIX', fraction_digits=0)
4235 Return the given decimal number formatted for a specific locale
4236 in compact form.
4237
4238 >>> format_compact_decimal(12345, format_type="short", locale='en_US')
4239 u'12K'
4240 >>> format_compact_decimal(12345, format_type="long", locale='en_US')
4241 u'12 thousand'
4242 >>> format_compact_decimal(12345, format_type="short", locale='en_US', fraction_digits=2)
4243 u'12.35K'
4244 >>> format_compact_decimal(1234567, format_type="short", locale="ja_JP")
4245 u'123万'
4246 >>> format_compact_decimal(2345678, format_type="long", locale="mk")
4247 u'2 милиони'
4248 >>> format_compact_decimal(21098765, format_type="long", locale="mk")
4249 u'21 милион'
4250
4251 Parameters
4252
4253 • number – the number to format
4254
4255 • format_type – Compact format to use (“short” or “long”)
4256
4257 • locale – the Locale object or locale identifier
4258
4259 • fraction_digits – Number of digits after the decimal
4260 point to use. Defaults to 0.
4261
4262 babel.numbers.format_currency(number, currency, format=None, lo‐
4263 cale='en_US_POSIX', currency_digits=True, format_type='standard', deci‐
4264 mal_quantization=True, group_separator=True)
4265 Return formatted currency value.
4266
4267 >>> format_currency(1099.98, 'USD', locale='en_US')
4268 u'$1,099.98'
4269 >>> format_currency(1099.98, 'USD', locale='es_CO')
4270 u'US$\xa01.099,98'
4271 >>> format_currency(1099.98, 'EUR', locale='de_DE')
4272 u'1.099,98\xa0\u20ac'
4273
4274 The format can also be specified explicitly. The currency is
4275 placed with the ‘¤’ sign. As the sign gets repeated the format
4276 expands (¤ being the symbol, ¤¤ is the currency abbreviation and
4277 ¤¤¤ is the full name of the currency):
4278
4279 >>> format_currency(1099.98, 'EUR', u'¤¤ #,##0.00', locale='en_US')
4280 u'EUR 1,099.98'
4281 >>> format_currency(1099.98, 'EUR', u'#,##0.00 ¤¤¤', locale='en_US')
4282 u'1,099.98 euros'
4283
4284 Currencies usually have a specific number of decimal digits.
4285 This function favours that information over the given format:
4286
4287 >>> format_currency(1099.98, 'JPY', locale='en_US')
4288 u'\xa51,100'
4289 >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
4290 u'1.099,98'
4291
4292 However, the number of decimal digits can be overriden from the
4293 currency information, by setting the last parameter to False:
4294
4295 >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
4296 u'\xa51,099.98'
4297 >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
4298 u'1.099,98'
4299
4300 If a format is not specified the type of currency format to use
4301 from the locale can be specified:
4302
4303 >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
4304 u'\u20ac1,099.98'
4305
4306 When the given currency format type is not available, an excep‐
4307 tion is raised:
4308
4309 >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
4310 Traceback (most recent call last):
4311 ...
4312 UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
4313
4314 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
4315 u'$101299.98'
4316
4317 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
4318 u'$101,299.98'
4319
4320 You can also pass format_type=’name’ to use long display names.
4321 The order of the number and currency name, along with the cor‐
4322 rect localized plural form of the currency name, is chosen ac‐
4323 cording to locale:
4324
4325 >>> format_currency(1, 'USD', locale='en_US', format_type='name')
4326 u'1.00 US dollar'
4327 >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
4328 u'1,099.98 US dollars'
4329 >>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
4330 u'us ga dollar 1,099.98'
4331
4332 By default the locale is allowed to truncate and round a
4333 high-precision number by forcing its format pattern onto the
4334 decimal part. You can bypass this behavior with the deci‐
4335 mal_quantization parameter:
4336
4337 >>> format_currency(1099.9876, 'USD', locale='en_US')
4338 u'$1,099.99'
4339 >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
4340 u'$1,099.9876'
4341
4342 Parameters
4343
4344 • number – the number to format
4345
4346 • currency – the currency code
4347
4348 • format – the format string to use
4349
4350 • locale – the Locale object or locale identifier
4351
4352 • currency_digits – use the currency’s natural number of
4353 decimal digits
4354
4355 • format_type – the currency format type to use
4356
4357 • decimal_quantization – Truncate and round high-preci‐
4358 sion numbers to the format pattern. Defaults to True.
4359
4360 • group_separator – Boolean to switch group separator
4361 on/off in a locale’s number format.
4362
4363 babel.numbers.format_percent(number, format=None, locale='en_US_POSIX',
4364 decimal_quantization=True, group_separator=True)
4365 Return formatted percent value for a specific locale.
4366
4367 >>> format_percent(0.34, locale='en_US')
4368 u'34%'
4369 >>> format_percent(25.1234, locale='en_US')
4370 u'2,512%'
4371 >>> format_percent(25.1234, locale='sv_SE')
4372 u'2\xa0512\xa0%'
4373
4374 The format pattern can also be specified explicitly:
4375
4376 >>> format_percent(25.1234, u'#,##0‰', locale='en_US')
4377 u'25,123‰'
4378
4379 By default the locale is allowed to truncate and round a
4380 high-precision number by forcing its format pattern onto the
4381 decimal part. You can bypass this behavior with the deci‐
4382 mal_quantization parameter:
4383
4384 >>> format_percent(23.9876, locale='en_US')
4385 u'2,399%'
4386 >>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
4387 u'2,398.76%'
4388
4389 >>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
4390 u'22929112%'
4391
4392 >>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
4393 u'22.929.112%'
4394
4395 Parameters
4396
4397 • number – the percent number to format
4398
4399 • format –
4400
4401 • locale – the Locale object or locale identifier
4402
4403 • decimal_quantization – Truncate and round high-preci‐
4404 sion numbers to the format pattern. Defaults to True.
4405
4406 • group_separator – Boolean to switch group separator
4407 on/off in a locale’s number format.
4408
4409 babel.numbers.format_scientific(number, format=None, lo‐
4410 cale='en_US_POSIX', decimal_quantization=True)
4411 Return value formatted in scientific notation for a specific lo‐
4412 cale.
4413
4414 >>> format_scientific(10000, locale='en_US')
4415 u'1E4'
4416
4417 The format pattern can also be specified explicitly:
4418
4419 >>> format_scientific(1234567, u'##0.##E00', locale='en_US')
4420 u'1.23E06'
4421
4422 By default the locale is allowed to truncate and round a
4423 high-precision number by forcing its format pattern onto the
4424 decimal part. You can bypass this behavior with the deci‐
4425 mal_quantization parameter:
4426
4427 >>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
4428 u'1.23E3'
4429 >>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
4430 u'1.2349876E3'
4431
4432 Parameters
4433
4434 • number – the number to format
4435
4436 • format –
4437
4438 • locale – the Locale object or locale identifier
4439
4440 • decimal_quantization – Truncate and round high-preci‐
4441 sion numbers to the format pattern. Defaults to True.
4442
4443 Number Parsing
4444 babel.numbers.parse_number(string, locale='en_US_POSIX')
4445 Parse localized number string into an integer.
4446
4447 >>> parse_number('1,099', locale='en_US')
4448 1099
4449 >>> parse_number('1.099', locale='de_DE')
4450 1099
4451
4452 When the given string cannot be parsed, an exception is raised:
4453
4454 >>> parse_number('1.099,98', locale='de')
4455 Traceback (most recent call last):
4456 ...
4457 NumberFormatError: '1.099,98' is not a valid number
4458
4459 Parameters
4460
4461 • string – the string to parse
4462
4463 • locale – the Locale object or locale identifier
4464
4465 Returns
4466 the parsed number
4467
4468 Raises NumberFormatError – if the string can not be converted to
4469 a number
4470
4471 babel.numbers.parse_decimal(string, locale='en_US_POSIX', strict=False)
4472 Parse localized decimal string into a decimal.
4473
4474 >>> parse_decimal('1,099.98', locale='en_US')
4475 Decimal('1099.98')
4476 >>> parse_decimal('1.099,98', locale='de')
4477 Decimal('1099.98')
4478 >>> parse_decimal('12 345,123', locale='ru')
4479 Decimal('12345.123')
4480
4481 When the given string cannot be parsed, an exception is raised:
4482
4483 >>> parse_decimal('2,109,998', locale='de')
4484 Traceback (most recent call last):
4485 ...
4486 NumberFormatError: '2,109,998' is not a valid decimal number
4487
4488 If strict is set to True and the given string contains a number
4489 formatted in an irregular way, an exception is raised:
4490
4491 >>> parse_decimal('30.00', locale='de', strict=True)
4492 Traceback (most recent call last):
4493 ...
4494 NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
4495
4496 >>> parse_decimal('0.00', locale='de', strict=True)
4497 Traceback (most recent call last):
4498 ...
4499 NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
4500
4501 Parameters
4502
4503 • string – the string to parse
4504
4505 • locale – the Locale object or locale identifier
4506
4507 • strict – controls whether numbers formatted in a weird
4508 way are accepted or rejected
4509
4510 Raises NumberFormatError – if the string can not be converted to
4511 a decimal number
4512
4513 Exceptions
4514 exception babel.numbers.NumberFormatError(message, suggestions=None)
4515 Exception raised when a string cannot be parsed into a number.
4516
4517 suggestions
4518 a list of properly formatted numbers derived from the in‐
4519 valid input
4520
4521 Data Access
4522 babel.numbers.get_currency_name(currency, count=None, lo‐
4523 cale='en_US_POSIX')
4524 Return the name used by the locale for the specified currency.
4525
4526 >>> get_currency_name('USD', locale='en_US')
4527 u'US Dollar'
4528
4529 New in version 0.9.4.
4530
4531
4532 Parameters
4533
4534 • currency – the currency code.
4535
4536 • count – the optional count. If provided the currency
4537 name will be pluralized to that number if possible.
4538
4539 • locale – the Locale object or locale identifier.
4540
4541 babel.numbers.get_currency_symbol(currency, locale='en_US_POSIX')
4542 Return the symbol used by the locale for the specified currency.
4543
4544 >>> get_currency_symbol('USD', locale='en_US')
4545 u'$'
4546
4547 Parameters
4548
4549 • currency – the currency code.
4550
4551 • locale – the Locale object or locale identifier.
4552
4553 babel.numbers.get_currency_unit_pattern(currency, count=None, lo‐
4554 cale='en_US_POSIX')
4555 Return the unit pattern used for long display of a currency
4556 value for a given locale. This is a string containing {0} where
4557 the numeric part should be substituted and {1} where the cur‐
4558 rency long display name should be substituted.
4559
4560 >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
4561 u'{0} {1}'
4562
4563 New in version 2.7.0.
4564
4565
4566 Parameters
4567
4568 • currency – the currency code.
4569
4570 • count – the optional count. If provided the unit pat‐
4571 tern for that number will be returned.
4572
4573 • locale – the Locale object or locale identifier.
4574
4575 babel.numbers.get_decimal_symbol(locale='en_US_POSIX')
4576 Return the symbol used by the locale to separate decimal frac‐
4577 tions.
4578
4579 >>> get_decimal_symbol('en_US')
4580 u'.'
4581
4582 Parameters
4583 locale – the Locale object or locale identifier
4584
4585 babel.numbers.get_plus_sign_symbol(locale='en_US_POSIX')
4586 Return the plus sign symbol used by the current locale.
4587
4588 >>> get_plus_sign_symbol('en_US')
4589 u'+'
4590
4591 Parameters
4592 locale – the Locale object or locale identifier
4593
4594 babel.numbers.get_minus_sign_symbol(locale='en_US_POSIX')
4595 Return the plus sign symbol used by the current locale.
4596
4597 >>> get_minus_sign_symbol('en_US')
4598 u'-'
4599
4600 Parameters
4601 locale – the Locale object or locale identifier
4602
4603 babel.numbers.get_territory_currencies(territory, start_date=None,
4604 end_date=None, tender=True, non_tender=False, include_details=False)
4605 Returns the list of currencies for the given territory that are
4606 valid for the given date range. In addition to that the cur‐
4607 rency database distinguishes between tender and non-tender cur‐
4608 rencies. By default only tender currencies are returned.
4609
4610 The return value is a list of all currencies roughly ordered by
4611 the time of when the currency became active. The longer the
4612 currency is being in use the more to the left of the list it
4613 will be.
4614
4615 The start date defaults to today. If no end date is given it
4616 will be the same as the start date. Otherwise a range can be
4617 defined. For instance this can be used to find the currencies
4618 in use in Austria between 1995 and 2011:
4619
4620 >>> from datetime import date
4621 >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
4622 ['ATS', 'EUR']
4623
4624 Likewise it’s also possible to find all the currencies in use on
4625 a single date:
4626
4627 >>> get_territory_currencies('AT', date(1995, 1, 1))
4628 ['ATS']
4629 >>> get_territory_currencies('AT', date(2011, 1, 1))
4630 ['EUR']
4631
4632 By default the return value only includes tender currencies.
4633 This however can be changed:
4634
4635 >>> get_territory_currencies('US')
4636 ['USD']
4637 >>> get_territory_currencies('US', tender=False, non_tender=True,
4638 ... start_date=date(2014, 1, 1))
4639 ['USN', 'USS']
4640
4641 New in version 2.0.
4642
4643
4644 Parameters
4645
4646 • territory – the name of the territory to find the cur‐
4647 rency for.
4648
4649 • start_date – the start date. If not given today is as‐
4650 sumed.
4651
4652 • end_date – the end date. If not given the start date
4653 is assumed.
4654
4655 • tender – controls whether tender currencies should be
4656 included.
4657
4658 • non_tender – controls whether non-tender currencies
4659 should be included.
4660
4661 • include_details – if set to True, instead of returning
4662 currency codes the return value will be dictionaries
4663 with detail information. In that case each dictionary
4664 will have the keys 'currency', 'from', 'to', and 'ten‐
4665 der'.
4666
4667 Pluralization Support
4668 The pluralization support provides functionality around the CLDR plu‐
4669 ralization rules. It can parse and evaluate pluralization rules, as
4670 well as convert them to other formats such as gettext.
4671
4672 Basic Interface
4673 class babel.plural.PluralRule(rules)
4674 Represents a set of language pluralization rules. The construc‐
4675 tor accepts a list of (tag, expr) tuples or a dict of CLDR
4676 rules. The resulting object is callable and accepts one parame‐
4677 ter with a positive or negative number (both integer and float)
4678 for the number that indicates the plural form for a string and
4679 returns the tag for the format:
4680
4681 >>> rule = PluralRule({'one': 'n is 1'})
4682 >>> rule(1)
4683 'one'
4684 >>> rule(2)
4685 'other'
4686
4687 Currently the CLDR defines these tags: zero, one, two, few, many
4688 and other where other is an implicit default. Rules should be
4689 mutually exclusive; for a given numeric value, only one rule
4690 should apply (i.e. the condition should only be true for one of
4691 the plural rule elements.
4692
4693 classmethod parse(rules)
4694 Create a PluralRule instance for the given rules. If the
4695 rules are a PluralRule object, that object is returned.
4696
4697 Parameters
4698 rules – the rules as list or dict, or a PluralRule
4699 object
4700
4701 Raises RuleError – if the expression is malformed
4702
4703 property rules
4704 The PluralRule as a dict of unicode plural rules.
4705
4706 >>> rule = PluralRule({'one': 'n is 1'})
4707 >>> rule.rules
4708 {'one': 'n is 1'}
4709
4710 property tags
4711 A set of explicitly defined tags in this rule. The im‐
4712 plicit default 'other' rules is not part of this set un‐
4713 less there is an explicit rule for it.
4714
4715 Conversion Functionality
4716 babel.plural.to_javascript(rule)
4717 Convert a list/dict of rules or a PluralRule object into a Java‐
4718 Script function. This function depends on no external library:
4719
4720 >>> to_javascript({'one': 'n is 1'})
4721 "(function(n) { return (n == 1) ? 'one' : 'other'; })"
4722
4723 Implementation detail: The function generated will probably
4724 evaluate expressions involved into range operations multiple
4725 times. This has the advantage that external helper functions
4726 are not required and is not a big performance hit for these sim‐
4727 ple calculations.
4728
4729 Parameters
4730 rule – the rules as list or dict, or a PluralRule object
4731
4732 Raises RuleError – if the expression is malformed
4733
4734 babel.plural.to_python(rule)
4735 Convert a list/dict of rules or a PluralRule object into a regu‐
4736 lar Python function. This is useful in situations where you
4737 need a real function and don’t are about the actual rule object:
4738
4739 >>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
4740 >>> func(1)
4741 'one'
4742 >>> func(3)
4743 'few'
4744 >>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
4745 >>> func(11)
4746 'one'
4747 >>> func(15)
4748 'few'
4749
4750 Parameters
4751 rule – the rules as list or dict, or a PluralRule object
4752
4753 Raises RuleError – if the expression is malformed
4754
4755 babel.plural.to_gettext(rule)
4756 The plural rule as gettext expression. The gettext expression
4757 is technically limited to integers and returns indices rather
4758 than tags.
4759
4760 >>> to_gettext({'one': 'n is 1', 'two': 'n is 2'})
4761 'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2);'
4762
4763 Parameters
4764 rule – the rules as list or dict, or a PluralRule object
4765
4766 Raises RuleError – if the expression is malformed
4767
4768 General Support Functionality
4769 Babel ships a few general helpers that are not being used by Babel it‐
4770 self but are useful in combination with functionality provided by it.
4771
4772 Convenience Helpers
4773 class babel.support.Format(locale, tzinfo=None)
4774 Wrapper class providing the various date and number formatting
4775 functions bound to a specific locale and time-zone.
4776
4777 >>> from babel.util import UTC
4778 >>> from datetime import date
4779 >>> fmt = Format('en_US', UTC)
4780 >>> fmt.date(date(2007, 4, 1))
4781 u'Apr 1, 2007'
4782 >>> fmt.decimal(1.2345)
4783 u'1.234'
4784
4785 currency(number, currency)
4786 Return a number in the given currency formatted for the
4787 locale.
4788
4789 date(date=None, format='medium')
4790 Return a date formatted according to the given pattern.
4791
4792 >>> from datetime import date
4793 >>> fmt = Format('en_US')
4794 >>> fmt.date(date(2007, 4, 1))
4795 u'Apr 1, 2007'
4796
4797 datetime(datetime=None, format='medium')
4798 Return a date and time formatted according to the given
4799 pattern.
4800
4801 >>> from datetime import datetime
4802 >>> from pytz import timezone
4803 >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
4804 >>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
4805 u'Apr 1, 2007, 11:30:00 AM'
4806
4807 decimal(number, format=None)
4808 Return a decimal number formatted for the locale.
4809
4810 >>> fmt = Format('en_US')
4811 >>> fmt.decimal(1.2345)
4812 u'1.234'
4813
4814 number(number)
4815 Return an integer number formatted for the locale.
4816
4817 >>> fmt = Format('en_US')
4818 >>> fmt.number(1099)
4819 u'1,099'
4820
4821 percent(number, format=None)
4822 Return a number formatted as percentage for the locale.
4823
4824 >>> fmt = Format('en_US')
4825 >>> fmt.percent(0.34)
4826 u'34%'
4827
4828 scientific(number)
4829 Return a number formatted using scientific notation for
4830 the locale.
4831
4832 time(time=None, format='medium')
4833 Return a time formatted according to the given pattern.
4834
4835 >>> from datetime import datetime
4836 >>> from pytz import timezone
4837 >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
4838 >>> fmt.time(datetime(2007, 4, 1, 15, 30))
4839 u'11:30:00 AM'
4840
4841 timedelta(delta, granularity='second', threshold=0.85, for‐
4842 mat='long', add_direction=False)
4843 Return a time delta according to the rules of the given
4844 locale.
4845
4846 >>> from datetime import timedelta
4847 >>> fmt = Format('en_US')
4848 >>> fmt.timedelta(timedelta(weeks=11))
4849 u'3 months'
4850
4851 class babel.support.LazyProxy(func, *args, **kwargs)
4852 Class for proxy objects that delegate to a specified function to
4853 evaluate the actual object.
4854
4855 >>> def greeting(name='world'):
4856 ... return 'Hello, %s!' % name
4857 >>> lazy_greeting = LazyProxy(greeting, name='Joe')
4858 >>> print(lazy_greeting)
4859 Hello, Joe!
4860 >>> u' ' + lazy_greeting
4861 u' Hello, Joe!'
4862 >>> u'(%s)' % lazy_greeting
4863 u'(Hello, Joe!)'
4864
4865 This can be used, for example, to implement lazy translation
4866 functions that delay the actual translation until the string is
4867 actually used. The rationale for such behavior is that the lo‐
4868 cale of the user may not always be available. In web applica‐
4869 tions, you only know the locale when processing a request.
4870
4871 The proxy implementation attempts to be as complete as possible,
4872 so that the lazy objects should mostly work as expected, for ex‐
4873 ample for sorting:
4874
4875 >>> greetings = [
4876 ... LazyProxy(greeting, 'world'),
4877 ... LazyProxy(greeting, 'Joe'),
4878 ... LazyProxy(greeting, 'universe'),
4879 ... ]
4880 >>> greetings.sort()
4881 >>> for greeting in greetings:
4882 ... print(greeting)
4883 Hello, Joe!
4884 Hello, universe!
4885 Hello, world!
4886
4887 Gettext Support
4888 class babel.support.Translations(fp=None, domain=None)
4889 An extended translation catalog class.
4890
4891 add(translations, merge=True)
4892 Add the given translations to the catalog.
4893
4894 If the domain of the translations is different than that
4895 of the current catalog, they are added as a catalog that
4896 is only accessible by the various d*gettext functions.
4897
4898 Parameters
4899
4900 • translations – the Translations instance with
4901 the messages to add
4902
4903 • merge – whether translations for message domains
4904 that have already been added should be merged
4905 with the existing translations
4906
4907 classmethod load(dirname=None, locales=None, domain=None)
4908 Load translations from the given directory.
4909
4910 Parameters
4911
4912 • dirname – the directory containing the MO files
4913
4914 • locales – the list of locales in order of pref‐
4915 erence (items in this list can be either Locale
4916 objects or locale strings)
4917
4918 • domain – the message domain (default: ‘mes‐
4919 sages’)
4920
4921 merge(translations)
4922 Merge the given translations into the catalog.
4923
4924 Message translations in the specified catalog override
4925 any messages with the same identifier in the existing
4926 catalog.
4927
4928 Parameters
4929 translations – the Translations instance with the
4930 messages to merge
4931
4932 Units
4933 The unit module provides functionality to format measurement units for
4934 different locales.
4935
4936 babel.units.format_unit(value, measurement_unit, length='long', for‐
4937 mat=None, locale='en_US_POSIX')
4938 Format a value of a given unit.
4939
4940 Values are formatted according to the locale’s usual pluraliza‐
4941 tion rules and number formats.
4942
4943 >>> format_unit(12, 'length-meter', locale='ro_RO')
4944 u'12 metri'
4945 >>> format_unit(15.5, 'length-mile', locale='fi_FI')
4946 u'15,5 mailia'
4947 >>> format_unit(1200, 'pressure-millimeter-ofhg', locale='nb')
4948 u'1\xa0200 millimeter kvikks\xf8lv'
4949 >>> format_unit(270, 'ton', locale='en')
4950 u'270 tons'
4951
4952 Number formats may be overridden with the format parameter.
4953
4954 >>> import decimal
4955 >>> format_unit(decimal.Decimal("-42.774"), 'temperature-celsius', 'short', format='#.0', locale='fr')
4956 u'-42,8\u202f\xb0C'
4957
4958 The locale’s usual pluralization rules are respected.
4959
4960 >>> format_unit(1, 'length-meter', locale='ro_RO')
4961 u'1 metru'
4962 >>> format_unit(0, 'length-mile', locale='cy')
4963 u'0 mi'
4964 >>> format_unit(1, 'length-mile', locale='cy')
4965 u'1 filltir'
4966 >>> format_unit(3, 'length-mile', locale='cy')
4967 u'3 milltir'
4968
4969 >>> format_unit(15, 'length-horse', locale='fi')
4970 Traceback (most recent call last):
4971 ...
4972 UnknownUnitError: length-horse is not a known unit in fi
4973
4974 New in version 2.2.0.
4975
4976
4977 Parameters
4978
4979 • value – the value to format. If this is a string, no
4980 number formatting will be attempted.
4981
4982 • measurement_unit – the code of a measurement unit.
4983 Known units can be found in the CLDR Unit Validity XML
4984 file:
4985 https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
4986
4987 • length – “short”, “long” or “narrow”
4988
4989 • format – An optional format, as accepted by format_dec‐
4990 imal.
4991
4992 • locale – the Locale object or locale identifier
4993
4994 babel.units.format_compound_unit(numerator_value, numerator_unit=None,
4995 denominator_value=1, denominator_unit=None, length='long', format=None,
4996 locale='en_US_POSIX')
4997 Format a compound number value, i.e. “kilometers per hour” or
4998 similar.
4999
5000 Both unit specifiers are optional to allow for formatting of ar‐
5001 bitrary values still according to the locale’s general “per”
5002 formatting specifier.
5003
5004 >>> format_compound_unit(7, denominator_value=11, length="short", locale="pt")
5005 '7/11'
5006
5007 >>> format_compound_unit(150, "kilometer", denominator_unit="hour", locale="sv")
5008 '150 kilometer per timme'
5009
5010 >>> format_compound_unit(150, "kilowatt", denominator_unit="year", locale="fi")
5011 '150 kilowattia / vuosi'
5012
5013 >>> format_compound_unit(32.5, "ton", 15, denominator_unit="hour", locale="en")
5014 '32.5 tons per 15 hours'
5015
5016 >>> format_compound_unit(160, denominator_unit="square-meter", locale="fr")
5017 '160 par m\xe8tre carr\xe9'
5018
5019 >>> format_compound_unit(4, "meter", "ratakisko", length="short", locale="fi")
5020 '4 m/ratakisko'
5021
5022 >>> format_compound_unit(35, "minute", denominator_unit="fathom", locale="sv")
5023 '35 minuter per famn'
5024
5025 >>> from babel.numbers import format_currency
5026 >>> format_compound_unit(format_currency(35, "JPY", locale="de"), denominator_unit="liter", locale="de")
5027 '35\xa0\xa5 pro Liter'
5028
5029 See
5030 https://www.unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
5031
5032 Parameters
5033
5034 • numerator_value – The numerator value. This may be a
5035 string, in which case it is considered preformatted and
5036 the unit is ignored.
5037
5038 • numerator_unit – The numerator unit. See format_unit.
5039
5040 • denominator_value – The denominator value. This may be
5041 a string, in which case it is considered preformatted
5042 and the unit is ignored.
5043
5044 • denominator_unit – The denominator unit. See for‐
5045 mat_unit.
5046
5047 • length – The formatting length. “short”, “long” or
5048 “narrow”
5049
5050 • format – An optional format, as accepted by format_dec‐
5051 imal.
5052
5053 • locale – the Locale object or locale identifier
5054
5055 Returns
5056 A formatted compound value.
5057
5058 babel.units.get_unit_name(measurement_unit, length='long', lo‐
5059 cale='en_US_POSIX')
5060 Get the display name for a measurement unit in the given locale.
5061
5062 >>> get_unit_name("radian", locale="en")
5063 'radians'
5064
5065 Unknown units will raise exceptions:
5066
5067 >>> get_unit_name("battery", locale="fi")
5068 Traceback (most recent call last):
5069 ...
5070 UnknownUnitError: battery/long is not a known unit/length in fi
5071
5072 Parameters
5073
5074 • measurement_unit – the code of a measurement unit.
5075 Known units can be found in the CLDR Unit Validity XML
5076 file:
5077 https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
5078
5079 • length – “short”, “long” or “narrow”
5080
5081 • locale – the Locale object or locale identifier
5082
5083 Returns
5084 The unit display name, or None.
5085
5087 Babel Development
5088 Babel as a library has a long history that goes back to the Trac
5089 project. Since then it has evolved into an independently developed
5090 project that implements data access for the CLDR project.
5091
5092 This document tries to explain as best as possible the general rules of
5093 the project in case you want to help out developing.
5094
5095 Tracking the CLDR
5096 Generally the goal of the project is to work as closely as possible
5097 with the CLDR data. This has in the past caused some frustrating prob‐
5098 lems because the data is entirely out of our hand. To minimize the
5099 frustration we generally deal with CLDR updates the following way:
5100
5101 • bump the CLDR data only with a major release of Babel.
5102
5103 • never perform custom bugfixes on the CLDR data.
5104
5105 • never work around CLDR bugs within Babel. If you find a problem in
5106 the data, report it upstream.
5107
5108 • adjust the parsing of the data as soon as possible, otherwise this
5109 will spiral out of control later. This is especially the case for
5110 bigger updates that change pluralization and more.
5111
5112 • try not to test against specific CLDR data that is likely to change.
5113
5114 Python Versions
5115 At the moment the following Python versions should be supported:
5116
5117 • Python 3.6 and up
5118
5119 • PyPy 3.7 and up
5120
5121 Unicode
5122 Unicode is a big deal in Babel. Here is how the rules are set up:
5123
5124 • internally everything is unicode that makes sense to have as unicode.
5125
5126 • Encode / decode at boundaries explicitly. Never assume an encoding
5127 in a way it cannot be overridden. utf-8 should be generally consid‐
5128 ered the default encoding.
5129
5130 Dates and Timezones
5131 Generally all timezone support in Babel is based on pytz which it just
5132 depends on. Babel should assume that timezone objects are pytz based
5133 because those are the only ones with an API that actually work cor‐
5134 rectly (due to the API problems with non UTC based timezones).
5135
5136 Assumptions to make:
5137
5138 • use UTC where possible.
5139
5140 • be super careful with local time. Do not use local time without
5141 knowing the exact timezone.
5142
5143 • time without date is a very useless construct. Do not try to support
5144 timezones for it. If you do, assume that the current local date is
5145 assumed and not utc date.
5146
5147 Babel Changelog
5148 Version 2.11.0
5149 Upcoming deprecation
5150 • This version, Babel 2.11, is the last version of Babel to support
5151 Python 3.6. Babel 2.12 will require Python 3.7 or newer.
5152
5153 Improvements
5154 • Support for hex escapes in JavaScript string literals ##877 - Prze‐
5155 myslaw Wegrzyn
5156
5157 • Add support for formatting decimals in compact form ##909 - Jonah
5158 Lawrence
5159
5160 • Adapt parse_date to handle ISO dates in ASCII format ##842 - Eric L.
5161
5162 •
5163
5164 Use ast instead of eval for Python string extraction ##915 - Aarni
5165 Koskela
5166
5167 • This also enables extraction from static f-strings.
5168 F-strings with expressions are silently ignored (but won’t
5169 raise an error as they used to).
5170
5171 Infrastructure
5172 • Tests: Use regular asserts and pytest.raises() ##875 – Aarni Koskela
5173
5174 • Wheels are now built in GitHub Actions ##888 – Aarni Koskela
5175
5176 • Small improvements to the CLDR downloader script ##894 – Aarni
5177 Koskela
5178
5179 • Remove antiquated __nonzero__ methods ##896 - Nikita Sobolev
5180
5181 • Remove superfluous __unicode__ declarations ##905 - Lukas Juhrich
5182
5183 • Mark package compatible with Python 3.11 ##913 - Aarni Koskela
5184
5185 • Quiesce pytest warnings ##916 - Aarni Koskela
5186
5187 Bugfixes
5188 • Use email.Message for pofile header parsing instead of the deprecated
5189 cgi.parse_header function. ##876 – Aarni Koskela
5190
5191 • Remove determining time zone via systemsetup on macOS ##914 - Aarni
5192 Koskela
5193
5194 Documentation
5195 • Update Python versions in documentation ##898 - Raphael Nestler
5196
5197 • Align BSD-3 license with OSI template ##912 - Lukas Kahwe Smith
5198
5199 Version 2.10.3
5200 This is a bugfix release for Babel 2.10.2, which was mistakenly pack‐
5201 aged with outdated locale data.
5202
5203 Thanks to Michał Górny for pointing this out and Jun Omae for verify‐
5204 ing.
5205
5206 This and future Babel PyPI packages will be built by a more automated
5207 process, which should make problems like this less likely to occur.
5208
5209 Version 2.10.2
5210 This is a bugfix release for Babel 2.10.1.
5211
5212 • Fallback count=”other” format in format_currency() (#872) - Jun Omae
5213
5214 • Fix get_period_id() with dayPeriodRule across 0:00 (#871) - Jun Omae
5215
5216 • Add support for b and B period symbols in time format (#869) - Jun
5217 Omae
5218
5219 • chore(docs/typo): Fixes a minor typo in a function comment (#864) -
5220 Frank Harrison
5221
5222 Version 2.10.1
5223 This is a bugfix release for Babel 2.10.0.
5224
5225 • Messages: Fix distutils import. Regressed in #843. (#852) - Nehal J
5226 Wani
5227
5228 • The wheel file is no longer marked as universal, since Babel only
5229 supports Python 3.
5230
5231 Version 2.10.0
5232 Upcoming deprecation
5233 • The get_next_timezone_transition() function is marked deprecated in
5234 this version and will be removed likely as soon as Babel 2.11. No
5235 replacement for this function is planned; based on discussion in
5236 #716, it’s likely the function is not used in any real code. (#852) -
5237 Aarni Koskela, Paul Ganssle
5238
5239 Improvements
5240 • CLDR: Upgrade to CLDR 41.0. (#853) - Aarni Koskela
5241
5242 • The c and e plural form operands introduced in CLDR 40 are
5243 parsed, but otherwise unsupported. (#826)
5244
5245 • Non-nominative forms of units are currently ignored.
5246
5247 • Messages: Implement --init-missing option for pybabel update (#785) -
5248 ruro
5249
5250 • Messages: For extract, you can now replace the built-in .* / _* ig‐
5251 nored directory patterns with ones of your own. (#832) - Aarni
5252 Koskela, Kinshuk Dua
5253
5254 • Messages: Add --check to verify if catalogs are up-to-date (#831) -
5255 Krzysztof Jagiełło
5256
5257 • Messages: Add --header-comment to override default header comment (‐
5258 #720) - Mohamed Hafez Morsy, Aarni Koskela
5259
5260 • Dates: parse_time now supports 12-hour clock, and is better at pars‐
5261 ing partial times. (#834) - Aarni Koskela, David Bauer, Arthur Jo‐
5262 vart
5263
5264 • Dates: parse_date and parse_time now raise ParseError, a subclass of
5265 ValueError, in certain cases. (#834) - Aarni Koskela
5266
5267 • Dates: parse_date and parse_time now accept the format parameter. (‐
5268 #834) - Juliette Monsel, Aarni Koskela
5269
5270 Infrastructure
5271 • The internal babel/_compat.py module is no more (#808) - Hugo van Ke‐
5272 menade
5273
5274 • Python 3.10 is officially supported (#809) - Hugo van Kemenade
5275
5276 • There’s now a friendly GitHub issue template. (#800) – Álvaro
5277 Mondéjar Rubio
5278
5279 • Don’t use the deprecated format_number function internally or in
5280 tests - Aarni Koskela
5281
5282 • Add GitHub URL for PyPi (#846) - Andrii Oriekhov
5283
5284 • Python 3.12 compatibility: Prefer setuptools imports to distutils im‐
5285 ports (#843) - Aarni Koskela
5286
5287 • Python 3.11 compatibility: Add deprecations to l*gettext variants (‐
5288 #835) - Aarni Koskela
5289
5290 • CI: Babel is now tested with PyPy 3.7. (#851) - Aarni Koskela
5291
5292 Bugfixes
5293 • Date formatting: Allow using other as fallback form (#827) - Aarni
5294 Koskela
5295
5296 • Locales: Locale.parse() normalizes variant tags to upper case (#829)
5297 - Aarni Koskela
5298
5299 • A typo in the plural format for Maltese is fixed. (#796) - Lukas Win‐
5300 kler
5301
5302 • Messages: Catalog date parsing is now timezone independent. (#701) -
5303 rachele-collin
5304
5305 • Messages: Fix duplicate locations when writing without lineno (#837)
5306 - Sigurd Ljødal
5307
5308 • Messages: Fix missing trailing semicolon in plural form headers (‐
5309 #848) - farhan5900
5310
5311 • CLI: Fix output of --list-locales to not be a bytes repr (#845) -
5312 Morgan Wahl
5313
5314 Documentation
5315 • Documentation is now correctly built again, and up to date (#830) -
5316 Aarni Koskela
5317
5318 Version 2.9.1
5319 Bugfixes
5320 • The internal locale-data loading functions now validate the name of
5321 the locale file to be loaded and only allow files within Babel’s data
5322 directory. Thank you to Chris Lyne of Tenable, Inc. for discovering
5323 the issue!
5324
5325 Version 2.9.0
5326 Upcoming version support changes
5327 • This version, Babel 2.9, is the last version of Babel to support
5328 Python 2.7, Python 3.4, and Python 3.5.
5329
5330 Improvements
5331 • CLDR: Use CLDR 37 – Aarni Koskela (#734)
5332
5333 • Dates: Handle ZoneInfo objects in get_timezone_location, get_time‐
5334 zone_name - Alessio Bogon (#741)
5335
5336 • Numbers: Add group_separator feature in number formatting - Abdullah
5337 Javed Nesar (#726)
5338
5339 Bugfixes
5340 • Dates: Correct default Format().timedelta format to ‘long’ to mute
5341 deprecation warnings – Aarni Koskela
5342
5343 • Import: Simplify iteration code in “import_cldr.py” – Felix Schwarz
5344
5345 • Import: Stop using deprecated ElementTree methods “getchildren()” and
5346 “getiterator()” – Felix Schwarz
5347
5348 • Messages: Fix unicode printing error on Python 2 without TTY. –
5349 Niklas Hambüchen
5350
5351 • Messages: Introduce invariant that _invalid_pofile() takes unicode
5352 line. – Niklas Hambüchen
5353
5354 • Tests: fix tests when using Python 3.9 – Felix Schwarz
5355
5356 • Tests: Remove deprecated ‘sudo: false’ from Travis configuration –
5357 Jon Dufresne
5358
5359 • Tests: Support Py.test 6.x – Aarni Koskela
5360
5361 • Utilities: LazyProxy: Handle AttributeError in specified func – Niki‐
5362 forov Konstantin (#724)
5363
5364 • Utilities: Replace usage of parser.suite with ast.parse – Miro
5365 Hrončok
5366
5367 Documentation
5368 • Update parse_number comments – Brad Martin (#708)
5369
5370 • Add __iter__ to Catalog documentation – @CyanNani123
5371
5372 Version 2.8.1
5373 This is solely a patch release to make running tests on Py.test 6+ pos‐
5374 sible.
5375
5376 Bugfixes
5377 • Support Py.test 6 - Aarni Koskela (#747, #750, #752)
5378
5379 Version 2.8.0
5380 Improvements
5381 • CLDR: Upgrade to CLDR 36.0 - Aarni Koskela (#679)
5382
5383 • Messages: Don’t even open files with the “ignore” extraction method -
5384 @sebleblanc (#678)
5385
5386 Bugfixes
5387 • Numbers: Fix formatting very small decimals when quantization is dis‐
5388 abled - Lev Lybin, @miluChen (#662)
5389
5390 • Messages: Attempt to sort all messages – Mario Frasca (#651, #606)
5391
5392 Docs
5393 • Add years to changelog - Romuald Brunet
5394
5395 • Note that installation requires pytz - Steve (Gadget) Barnes
5396
5397 Version 2.7.0
5398 Possibly incompatible changes
5399 These may be backward incompatible in some cases, as some more-or-less
5400 internal APIs have changed. Please feel free to file issues if you bump
5401 into anything strange and we’ll try to help!
5402
5403 • General: Internal uses of babel.util.odict have been replaced with
5404 collections.OrderedDict from The Python standard library.
5405
5406 Improvements
5407 • CLDR: Upgrade to CLDR 35.1 - Alberto Mardegan, Aarni Koskela (#626,
5408 #643)
5409
5410 • General: allow anchoring path patterns to the start of a string -
5411 Brian Cappello (#600)
5412
5413 • General: Bumped version requirement on pytz - @chrisbrake (#592)
5414
5415 • Messages: pybabel compile: exit with code 1 if errors were encoun‐
5416 tered - Aarni Koskela (#647)
5417
5418 • Messages: Add omit-header to update_catalog - Cédric Krier (#633)
5419
5420 • Messages: Catalog update: keep user comments from destination by de‐
5421 fault - Aarni Koskela (#648)
5422
5423 • Messages: Skip empty message when writing mo file - Cédric Krier (‐
5424 #564)
5425
5426 • Messages: Small fixes to avoid crashes on badly formatted .po files -
5427 Bryn Truscott (#597)
5428
5429 • Numbers: parse_decimal() strict argument and suggestions - Charly C
5430 (#590)
5431
5432 • Numbers: don’t repeat suggestions in parse_decimal strict - Serban
5433 Constantin (#599)
5434
5435 • Numbers: implement currency formatting with long display names - Luke
5436 Plant (#585)
5437
5438 • Numbers: parse_decimal(): assume spaces are equivalent to non-break‐
5439 ing spaces when not in strict mode - Aarni Koskela (#649)
5440
5441 • Performance: Cache locale_identifiers() - Aarni Koskela (#644)
5442
5443 Bugfixes
5444 • CLDR: Skip alt=… for week data (minDays, firstDay, weekendStart,
5445 weekendEnd) - Aarni Koskela (#634)
5446
5447 • Dates: Fix wrong weeknumber for 31.12.2018 - BT-sschmid (#621)
5448
5449 • Locale: Avoid KeyError trying to get data on WindowsXP - mondeja (‐
5450 #604)
5451
5452 • Locale: get_display_name(): Don’t attempt to concatenate variant in‐
5453 formation to None - Aarni Koskela (#645)
5454
5455 • Messages: pofile: Add comparison operators to _NormalizedString -
5456 Aarni Koskela (#646)
5457
5458 • Messages: pofile: don’t crash when message.locations can’t be sorted
5459 - Aarni Koskela (#646)
5460
5461 Tooling & docs
5462 • Docs: Remove all references to deprecated easy_install - Jon Dufresne
5463 (#610)
5464
5465 • Docs: Switch print statement in docs to print function - NotAFile
5466
5467 • Docs: Update all pypi.python.org URLs to pypi.org - Jon Dufresne (‐
5468 #587)
5469
5470 • Docs: Use https URLs throughout project where available - Jon
5471 Dufresne (#588)
5472
5473 • Support: Add testing and document support for Python 3.7 - Jon
5474 Dufresne (#611)
5475
5476 • Support: Test on Python 3.8-dev - Aarni Koskela (#642)
5477
5478 • Support: Using ABCs from collections instead of collections.abc is
5479 deprecated. - Julien Palard (#609)
5480
5481 • Tests: Fix conftest.py compatibility with pytest 4.3 - Miro Hrončok
5482 (#635)
5483
5484 • Tests: Update pytest and pytest-cov - Miro Hrončok (#635)
5485
5486 Version 2.6.0
5487 Possibly incompatible changes
5488 These may be backward incompatible in some cases, as some more-or-less
5489 internal APIs have changed. Please feel free to file issues if you
5490 bump into anything strange and we’ll try to help!
5491
5492 • Numbers: Refactor decimal handling code and allow bypass of decimal
5493 quantization. (@kdeldycke) (PR #538)
5494
5495 • Messages: allow processing files that are in locales unknown to Babel
5496 (@akx) (PR #557)
5497
5498 • General: Drop support for EOL Python 2.6 and 3.3 (@hugovk) (PR #546)
5499
5500 Other changes
5501 • CLDR: Use CLDR 33 (@akx) (PR #581)
5502
5503 • Lists: Add support for various list styles other than the default
5504 (@akx) (#552)
5505
5506 • Messages: Add new PoFileError exception (@Bedrock02) (PR #532)
5507
5508 • Times: Simplify Linux distro specific explicit timezone setting
5509 search (@scop) (PR #528)
5510
5511 Bugfixes
5512 • CLDR: avoid importing alt=narrow currency symbols (@akx) (PR #558)
5513
5514 • CLDR: ignore non-Latin numbering systems (@akx) (PR #579)
5515
5516 • Docs: Fix improper example for date formatting (@PTrottier) (PR #574)
5517
5518 • Tooling: Fix some deprecation warnings (@akx) (PR #580)
5519
5520 Tooling & docs
5521 • Add explicit signatures to some date autofunctions (@xmo-odoo) (PR
5522 #554)
5523
5524 • Include license file in the generated wheel package (@jdufresne) (PR
5525 #539)
5526
5527 • Python 3.6 invalid escape sequence deprecation fixes (@scop) (PR
5528 #528)
5529
5530 • Test and document all supported Python versions (@jdufresne) (PR
5531 #540)
5532
5533 • Update copyright header years and authors file (@akx) (PR #559)
5534
5535 Version 2.5.3
5536 This is a maintenance release that reverts undesired API-breaking
5537 changes that slipped into 2.5.2 (see #550).
5538
5539 It is based on v2.5.1 (f29eccd) with commits 7cedb84, 29da2d2 and
5540 edfb518 cherry-picked on top.
5541
5542 Version 2.5.2
5543 Bugfixes
5544 • Revert the unnecessary PyInstaller fixes from 2.5.0 and 2.5.1 (#533)
5545 (@yagebu)
5546
5547 Version 2.5.1
5548 Minor Improvements and bugfixes
5549 • Use a fixed datetime to avoid test failures (#520) (@narendravardi)
5550
5551 • Parse multi-line __future__ imports better (#519) (@akx)
5552
5553 • Fix validate_currency docstring (#522)
5554
5555 • Allow normalize_locale and exists to handle various unexpected inputs
5556 (#523) (@suhojm)
5557
5558 • Make PyInstaller support more robust (#525, #526) (@thijstriemstra,
5559 @akx)
5560
5561 Version 2.5.0
5562 New Features
5563 • Numbers: Add currency utilities and helpers (#491) (@kdeldycke)
5564
5565 • Support PyInstaller (#500, #505) (@wodo)
5566
5567 Minor Improvements and bugfixes
5568 • Dates: Add __str__ to DateTimePattern (#515) (@sfermigier)
5569
5570 • Dates: Fix an invalid string to bytes comparison when parsing TZ
5571 files on Py3 (#498) (@rowillia)
5572
5573 • Dates: Formatting zero-padded components of dates is faster (#517)
5574 (@akx)
5575
5576 • Documentation: Fix “Good Commits” link in CONTRIBUTING.md (#511)
5577 (@naryanacharya6)
5578
5579 • Documentation: Fix link to Python gettext module (#512) (@Linkid)
5580
5581 • Messages: Allow both dash and underscore separated locale identifiers
5582 in pofiles (#489, #490) (@akx)
5583
5584 • Messages: Extract Python messages in nested gettext calls (#488)
5585 (@sublee)
5586
5587 • Messages: Fix in-place editing of dir list while iterating (#476,
5588 #492) (@MarcDufresne)
5589
5590 • Messages: Stabilize sort order (#482) (@xavfernandez)
5591
5592 • Time zones: Honor the no-inherit marker for metazone names (#405)
5593 (@akx)
5594
5595 Version 2.4.0
5596 New Features
5597 Some of these changes might break your current code and/or tests.
5598
5599 • CLDR: CLDR 29 is now used instead of CLDR 28 (#405) (@akx)
5600
5601 • Messages: Add option ‘add_location’ for location line formatting (‐
5602 #438, #459) (@rrader, @alxpy)
5603
5604 • Numbers: Allow full control of decimal behavior (#410) (@etanol)
5605
5606 Minor Improvements and bugfixes
5607 • Documentation: Improve Date Fields descriptions (#450) (@ldwoolley)
5608
5609 • Documentation: Typo fixes and documentation improvements (#406, #412,
5610 #403, #440, #449, #463) (@zyegfryed, @adamchainz, @jwilk, @akx, @ro‐
5611 ramirez, @abhishekcs10)
5612
5613 • Messages: Default to UTF-8 source encoding instead of ISO-8859-1 (‐
5614 #399) (@asottile)
5615
5616 • Messages: Ensure messages are extracted in the order they were passed
5617 in (#424) (@ngrilly)
5618
5619 • Messages: Message extraction for JSX files is improved (#392, #396,
5620 #425) (@karloskar, @georgschoelly)
5621
5622 • Messages: PO file reading supports multi-line obsolete units (#429)
5623 (@mbirtwell)
5624
5625 • Messages: Python message extractor respects unicode_literals in __fu‐
5626 ture__ (#427) (@sublee)
5627
5628 • Messages: Roundtrip Language headers (#420) (@kruton)
5629
5630 • Messages: units before obsolete units are no longer erroneously
5631 marked obsolete (#452) (@mbirtwell)
5632
5633 • Numbers: parse_pattern now preserves the full original pattern (#414)
5634 (@jtwang)
5635
5636 • Numbers: Fix float conversion in extract_operands (#435) (@akx)
5637
5638 • Plurals: Fix plural forms for Czech and Slovak locales (#373) (@yk‐
5639 shatroff)
5640
5641 • Plurals: More plural form fixes based on Mozilla and CLDR references
5642 (#431) (@mshenfield)
5643
5644 Internal improvements
5645 • Local times are constructed correctly in tests (#411) (@etanol)
5646
5647 • Miscellaneous small improvements (#437) (@scop)
5648
5649 • Regex flags are extracted from the regex strings (#462) (@singing‐
5650 wolfboy)
5651
5652 • The PO file reader is now a class and has seen some refactoring (‐
5653 #429, #452) (@mbirtwell)
5654
5655 Version 2.3.4
5656 (Bugfix release, released on April 22th 2016)
5657
5658 Bugfixes
5659 • CLDR: The lxml library is no longer used for CLDR importing, so it
5660 should not cause strange failures either. Thanks to @aronbierbaum for
5661 the bug report and @jtwang for the fix. (‐
5662 https://github.com/python-babel/babel/pull/393)
5663
5664 • CLI: Every last single CLI usage regression should now be gone, and
5665 both distutils and stand-alone CLIs should work as they have in the
5666 past. Thanks to @paxswill and @ajaeger for bug reports. (‐
5667 https://github.com/python-babel/babel/pull/389)
5668
5669 Version 2.3.3
5670 (Bugfix release, released on April 12th 2016)
5671
5672 Bugfixes
5673 • CLI: Usage regressions that had snuck in between 2.2 and 2.3 should
5674 be no more. (https://github.com/python-babel/babel/pull/386) Thanks
5675 to @ajaeger, @sebdiem and @jcristovao for bug reports and patches.
5676
5677 Version 2.3.2
5678 (Bugfix release, released on April 9th 2016)
5679
5680 Bugfixes
5681 • Dates: Period (am/pm) formatting was broken in certain locales
5682 (namely zh_TW). Thanks to @jun66j5 for the bug report. (#378, #379)
5683
5684 Version 2.3.1
5685 (Bugfix release because of deployment problems, released on April 8th
5686 2016)
5687
5688 Version 2.3
5689 (Feature release, released on April 8th 2016)
5690
5691 Internal improvements
5692 • The CLI frontend and Distutils commands use a shared implementation
5693 (https://github.com/python-babel/babel/pull/311)
5694
5695 • PyPy3 is supported (https://github.com/python-babel/babel/pull/343)
5696
5697 Features
5698 • CLDR: Add an API for territory language data (‐
5699 https://github.com/python-babel/babel/pull/315)
5700
5701 • Core: Character order and measurement system data is imported and ex‐
5702 posed (https://github.com/python-babel/babel/pull/368)
5703
5704 • Dates: Add an API for time interval formatting (‐
5705 https://github.com/python-babel/babel/pull/316)
5706
5707 • Dates: More pattern formats and lengths are supported (‐
5708 https://github.com/python-babel/babel/pull/347)
5709
5710 • Dates: Period IDs are imported and exposed (‐
5711 https://github.com/python-babel/babel/pull/349)
5712
5713 • Dates: Support for date-time skeleton formats has been added (‐
5714 https://github.com/python-babel/babel/pull/265)
5715
5716 • Dates: Timezone formatting has been improved (‐
5717 https://github.com/python-babel/babel/pull/338)
5718
5719 • Messages: JavaScript extraction now supports dotted names, ES6 tem‐
5720 plate strings and JSX tags (‐
5721 https://github.com/python-babel/babel/pull/332)
5722
5723 • Messages: npgettext is recognized by default (‐
5724 https://github.com/python-babel/babel/pull/341)
5725
5726 • Messages: The CLI learned to accept multiple domains (‐
5727 https://github.com/python-babel/babel/pull/335)
5728
5729 • Messages: The extraction commands now accept filenames in addition to
5730 directories (https://github.com/python-babel/babel/pull/324)
5731
5732 • Units: A new API for unit formatting is implemented (‐
5733 https://github.com/python-babel/babel/pull/369)
5734
5735 Bugfixes
5736 • Core: Mixed-case locale IDs work more reliably (‐
5737 https://github.com/python-babel/babel/pull/361)
5738
5739 • Dates: S…S formats work correctly now (‐
5740 https://github.com/python-babel/babel/pull/360)
5741
5742 • Messages: All messages are now sorted correctly if sorting has been
5743 specified (https://github.com/python-babel/babel/pull/300)
5744
5745 • Messages: Fix the unexpected behavior caused by catalog header updat‐
5746 ing (e0e7ef1) (https://github.com/python-babel/babel/pull/320)
5747
5748 • Messages: Gettext operands are now generated correctly (‐
5749 https://github.com/python-babel/babel/pull/295)
5750
5751 • Messages: Message extraction has been taught to detect encodings bet‐
5752 ter (https://github.com/python-babel/babel/pull/274)
5753
5754 Version 2.2
5755 (Feature release, released on January 2nd 2016)
5756
5757 Bugfixes
5758 • General: Add __hash__ to Locale. (#303) (2aa8074)
5759
5760 • General: Allow files with BOM if they’re UTF-8 (#189) (da87edd)
5761
5762 • General: localedata directory is now locale-data (#109) (2d1882e)
5763
5764 • General: odict: Fix pop method (0a9e97e)
5765
5766 • General: Removed uses of datetime.date class from .dat files (#174)
5767 (94f6830)
5768
5769 • Messages: Fix plural selection for Chinese (531f666)
5770
5771 • Messages: Fix typo and add semicolon in plural_forms (5784501)
5772
5773 • Messages: Flatten NullTranslations.files into a list (ad11101)
5774
5775 • Times: FixedOffsetTimezone: fix display of negative offsets (d816803)
5776
5777 Features
5778 • CLDR: Update to CLDR 28 (#292) (9f7f4d0)
5779
5780 • General: Add __copy__ and __deepcopy__ to LazyProxy. (a1cc3f1)
5781
5782 • General: Add official support for Python 3.4 and 3.5
5783
5784 • General: Improve odict performance by making key search O(1)
5785 (6822b7f)
5786
5787 • Locale: Add an ordinal_form property to Locale (#270) (b3f3430)
5788
5789 • Locale: Add support for list formatting (37ce4fa, be6e23d)
5790
5791 • Locale: Check inheritance exceptions first (3ef0d6d)
5792
5793 • Messages: Allow file locations without line numbers (#279) (79bc781)
5794
5795 • Messages: Allow passing a callable to extract() (#289) (3f58516)
5796
5797 • Messages: Support ‘Language’ header field of PO files (#76) (3ce842b)
5798
5799 • Messages: Update catalog headers from templates (e0e7ef1)
5800
5801 • Numbers: Properly load and expose currency format types (#201)
5802 (df676ab)
5803
5804 • Numbers: Use cdecimal by default when available (b6169be)
5805
5806 • Numbers: Use the CLDR’s suggested number of decimals for format_cur‐
5807 rency (#139) (201ed50)
5808
5809 • Times: Add format_timedelta(format=’narrow’) support (edc5eb5)
5810
5811 Version 2.1
5812 (Bugfix/minor feature release, released on September 25th 2015)
5813
5814 • Parse and honour the locale inheritance exceptions (#97)
5815
5816 • Fix Locale.parse using global.dat incompatible types (#174)
5817
5818 • Fix display of negative offsets in FixedOffsetTimezone (#214)
5819
5820 • Improved odict performance which is used during localization file
5821 build, should improve compilation time for large projects
5822
5823 • Add support for “narrow” format for format_timedelta
5824
5825 • Add universal wheel support
5826
5827 • Support ‘Language’ header field in .PO files (fixes #76)
5828
5829 • Test suite enhancements (coverage, broken tests fixed, etc)
5830
5831 • Documentation updated
5832
5833 Version 2.0
5834 (Released on July 27th 2015, codename Second Coming)
5835
5836 • Added support for looking up currencies that belong to a territory
5837 through the babel.numbers.get_territory_currencies() function.
5838
5839 • Improved Python 3 support.
5840
5841 • Fixed some broken tests for timezone behavior.
5842
5843 • Improved various smaller things for dealing with dates.
5844
5845 Version 1.4
5846 (bugfix release, release date to be decided)
5847
5848 • Fixed a bug that caused deprecated territory codes not being con‐
5849 verted properly by the subtag resolving. This for instance showed up
5850 when trying to use und_UK as a language code which now properly re‐
5851 solves to en_GB.
5852
5853 • Fixed a bug that made it impossible to import the CLDR data from
5854 scratch on windows systems.
5855
5856 Version 1.3
5857 (bugfix release, released on July 29th 2013)
5858
5859 • Fixed a bug in likely-subtag resolving for some common locales. This
5860 primarily makes zh_CN work again which was broken due to how it was
5861 defined in the likely subtags combined with our broken resolving.
5862 This fixes #37.
5863
5864 • Fixed a bug that caused pybabel to break when writing to stdout on
5865 Python 3.
5866
5867 • Removed a stray print that was causing issues when writing to stdout
5868 for message catalogs.
5869
5870 Version 1.2
5871 (bugfix release, released on July 27th 2013)
5872
5873 • Included all tests in the tarball. Previously the include skipped
5874 past recursive folders.
5875
5876 • Changed how tests are invoked and added separate standalone test com‐
5877 mand. This simplifies testing of the package for linux distributors.
5878
5879 Version 1.1
5880 (bugfix release, released on July 27th 2013)
5881
5882 • added dummy version requirements for pytz so that it installs on pip
5883 1.4.
5884
5885 • Included tests in the tarball.
5886
5887 Version 1.0
5888 (Released on July 26th 2013, codename Revival)
5889
5890 • support python 2.6, 2.7, 3.3+ and pypy - drop all other versions
5891
5892 • use tox for testing on different pythons
5893
5894 • Added support for the locale plural rules defined by the CLDR.
5895
5896 • Added format_timedelta function to support localized formatting of
5897 relative times with strings such as “2 days” or “1 month” (ticket
5898 #126).
5899
5900 • Fixed negative offset handling of Catalog._set_mime_headers (ticket
5901 #165).
5902
5903 • Fixed the case where messages containing square brackets would break
5904 with an unpack error.
5905
5906 • updated to CLDR 23
5907
5908 • Make the CLDR import script work with Python 2.7.
5909
5910 • Fix various typos.
5911
5912 • Sort output of list-locales.
5913
5914 • Make the POT-Creation-Date of the catalog being updated equal to
5915 POT-Creation-Date of the template used to update (ticket #148).
5916
5917 • Use a more explicit error message if no option or argument (command)
5918 is passed to pybabel (ticket #81).
5919
5920 • Keep the PO-Revision-Date if it is not the default value (ticket
5921 #148).
5922
5923 • Make –no-wrap work by reworking –width’s default and mimic xgettext’s
5924 behaviour of always wrapping comments (ticket #145).
5925
5926 • Add –project and –version options for commandline (ticket #173).
5927
5928 • Add a __ne__() method to the Local class.
5929
5930 • Explicitly sort instead of using sorted() and don’t assume ordering
5931 (Jython compatibility).
5932
5933 • Removed ValueError raising for string formatting message checkers if
5934 the string does not contain any string formattings (ticket #150).
5935
5936 • Fix Serbian plural forms (ticket #213).
5937
5938 • Small speed improvement in format_date() (ticket #216).
5939
5940 • Fix so frontend.CommandLineInterface.run does not accumulate logging
5941 handlers (ticket #227, reported with initial patch by dfraser)
5942
5943 • Fix exception if environment contains an invalid locale setting (‐
5944 ticket #200)
5945
5946 • use cPickle instead of pickle for better performance (ticket #225)
5947
5948 • Only use bankers round algorithm as a tie breaker if there are two
5949 nearest numbers, round as usual if there is only one nearest number
5950 (ticket #267, patch by Martin)
5951
5952 • Allow disabling cache behaviour in LazyProxy (ticket #208, initial
5953 patch from Pedro Algarvio)
5954
5955 • Support for context-aware methods during message extraction (ticket
5956 #229, patch from David Rios)
5957
5958 • “init” and “update” commands support “–no-wrap” option (ticket #289)
5959
5960 • fix formatting of fraction in format_decimal() if the input value is
5961 a float with more than 7 significant digits (ticket #183)
5962
5963 • fix format_date() with datetime parameter (ticket #282, patch from
5964 Xavier Morel)
5965
5966 • fix format_decimal() with small Decimal values (ticket #214, patch
5967 from George Lund)
5968
5969 • fix handling of messages containing ‘\n’ (ticket #198)
5970
5971 • handle irregular multi-line msgstr (no “” as first line) gracefully
5972 (ticket #171)
5973
5974 • parse_decimal() now returns Decimals not floats, API change (ticket
5975 #178)
5976
5977 • no warnings when running setup.py without installed setuptools (‐
5978 ticket #262)
5979
5980 • modified Locale.__eq__ method so Locales are only equal if all of
5981 their attributes (language, territory, script, variant) are equal
5982
5983 • resort to hard-coded message extractors/checkers if pkg_resources is
5984 installed but no egg-info was found (ticket #230)
5985
5986 • format_time() and format_datetime() now accept also floats (ticket
5987 #242)
5988
5989 • add babel.support.NullTranslations class similar to gettext.Null‐
5990 Translations but with all of Babel’s new gettext methods (ticket
5991 #277)
5992
5993 • “init” and “update” commands support “–width” option (ticket #284)
5994
5995 • fix ‘input_dirs’ option for setuptools integration (ticket #232, ini‐
5996 tial patch by Étienne Bersac)
5997
5998 • ensure .mo file header contains the same information as the source
5999 .po file (ticket #199)
6000
6001 • added support for get_language_name() on the locale objects.
6002
6003 • added support for get_territory_name() on the locale objects.
6004
6005 • added support for get_script_name() on the locale objects.
6006
6007 • added pluralization support for currency names and added a ‘¤¤¤’ pat‐
6008 tern for currencies that includes the full name.
6009
6010 • depend on pytz now and wrap it nicer. This gives us improved support
6011 for things like timezone transitions and an overall nicer API.
6012
6013 • Added support for explicit charset to PO file reading.
6014
6015 • Added experimental Python 3 support.
6016
6017 • Added better support for returning timezone names.
6018
6019 • Don’t throw away a Catalog’s obsolete messages when updating it.
6020
6021 • Added basic likelySubtag resolving when doing locale parsing and no
6022 match can be found.
6023
6024 Version 0.9.6
6025 (released on March 17th 2011)
6026
6027 • Backport r493-494: documentation typo fixes.
6028
6029 • Make the CLDR import script work with Python 2.7.
6030
6031 • Fix various typos.
6032
6033 • Fixed Python 2.3 compatibility (ticket #146, ticket #233).
6034
6035 • Sort output of list-locales.
6036
6037 • Make the POT-Creation-Date of the catalog being updated equal to
6038 POT-Creation-Date of the template used to update (ticket #148).
6039
6040 • Use a more explicit error message if no option or argument (command)
6041 is passed to pybabel (ticket #81).
6042
6043 • Keep the PO-Revision-Date if it is not the default value (ticket
6044 #148).
6045
6046 • Make –no-wrap work by reworking –width’s default and mimic xgettext’s
6047 behaviour of always wrapping comments (ticket #145).
6048
6049 • Fixed negative offset handling of Catalog._set_mime_headers (ticket
6050 #165).
6051
6052 • Add –project and –version options for commandline (ticket #173).
6053
6054 • Add a __ne__() method to the Local class.
6055
6056 • Explicitly sort instead of using sorted() and don’t assume ordering
6057 (Python 2.3 and Jython compatibility).
6058
6059 • Removed ValueError raising for string formatting message checkers if
6060 the string does not contain any string formattings (ticket #150).
6061
6062 • Fix Serbian plural forms (ticket #213).
6063
6064 • Small speed improvement in format_date() (ticket #216).
6065
6066 • Fix number formatting for locales where CLDR specifies alt or draft
6067 items (ticket #217)
6068
6069 • Fix bad check in format_time (ticket #257, reported with patch and
6070 tests by jomae)
6071
6072 • Fix so frontend.CommandLineInterface.run does not accumulate logging
6073 handlers (ticket #227, reported with initial patch by dfraser)
6074
6075 • Fix exception if environment contains an invalid locale setting (‐
6076 ticket #200)
6077
6078 Version 0.9.5
6079 (released on April 6th 2010)
6080
6081 • Fixed the case where messages containing square brackets would break
6082 with an unpack error.
6083
6084 • Backport of r467: Fuzzy matching regarding plurals should NOT be
6085 checked against len(message.id) because this is always 2, instead,
6086 it’s should be checked against catalog.num_plurals (ticket #212).
6087
6088 Version 0.9.4
6089 (released on August 25th 2008)
6090
6091 • Currency symbol definitions that is defined with choice patterns in
6092 the CLDR data are no longer imported, so the symbol code will be used
6093 instead.
6094
6095 • Fixed quarter support in date formatting.
6096
6097 • Fixed a serious memory leak that was introduces by the support for
6098 CLDR aliases in 0.9.3 (ticket #128).
6099
6100 • Locale modifiers such as “@euro” are now stripped from locale identi‐
6101 fiers when parsing (ticket #136).
6102
6103 • The system locales “C” and “POSIX” are now treated as aliases for
6104 “en_US_POSIX”, for which the CLDR provides the appropriate data.
6105 Thanks to Manlio Perillo for the suggestion.
6106
6107 • Fixed JavaScript extraction for regular expression literals (ticket
6108 #138) and concatenated strings.
6109
6110 • The Translation class in babel.support can now manage catalogs with
6111 different message domains, and exposes the family of d*gettext func‐
6112 tions (ticket #137).
6113
6114 Version 0.9.3
6115 (released on July 9th 2008)
6116
6117 • Fixed invalid message extraction methods causing an UnboundLocalEr‐
6118 ror.
6119
6120 • Extraction method specification can now use a dot instead of the
6121 colon to separate module and function name (ticket #105).
6122
6123 • Fixed message catalog compilation for locales with more than two plu‐
6124 ral forms (ticket #95).
6125
6126 • Fixed compilation of message catalogs for locales with more than two
6127 plural forms where the translations were empty (ticket #97).
6128
6129 • The stripping of the comment tags in comments is optional now and is
6130 done for each line in a comment.
6131
6132 • Added a JavaScript message extractor.
6133
6134 • Updated to CLDR 1.6.
6135
6136 • Fixed timezone calculations when formatting datetime and time values.
6137
6138 • Added a get_plural function into the plurals module that returns the
6139 correct plural forms for a locale as tuple.
6140
6141 • Added support for alias definitions in the CLDR data files, meaning
6142 that the chance for items missing in certain locales should be
6143 greatly reduced (ticket #68).
6144
6145 Version 0.9.2
6146 (released on February 4th 2008)
6147
6148 • Fixed catalogs’ charset values not being recognized (ticket #66).
6149
6150 • Numerous improvements to the default plural forms.
6151
6152 • Fixed fuzzy matching when updating message catalogs (ticket #82).
6153
6154 • Fixed bug in catalog updating, that in some cases pulled in transla‐
6155 tions from different catalogs based on the same template.
6156
6157 • Location lines in PO files do no longer get wrapped at hyphens in
6158 file names (ticket #79).
6159
6160 • Fixed division by zero error in catalog compilation on empty catalogs
6161 (ticket #60).
6162
6163 Version 0.9.1
6164 (released on September 7th 2007)
6165
6166 • Fixed catalog updating when a message is merged that was previously
6167 simple but now has a plural form, for example by moving from gettext
6168 to ngettext, or vice versa.
6169
6170 • Fixed time formatting for 12 am and 12 pm.
6171
6172 • Fixed output encoding of the pybabel –list-locales command.
6173
6174 • MO files are now written in binary mode on windows (ticket #61).
6175
6176 Version 0.9
6177 (released on August 20th 2007)
6178
6179 • The new_catalog distutils command has been renamed to init_catalog
6180 for consistency with the command-line frontend.
6181
6182 • Added compilation of message catalogs to MO files (ticket #21).
6183
6184 • Added updating of message catalogs from POT files (ticket #22).
6185
6186 • Support for significant digits in number formatting.
6187
6188 • Apply proper “banker’s rounding” in number formatting in a
6189 cross-platform manner.
6190
6191 • The number formatting functions now also work with numbers repre‐
6192 sented by Python Decimal objects (ticket #53).
6193
6194 • Added extensible infrastructure for validating translation catalogs.
6195
6196 • Fixed the extractor not filtering out messages that didn’t validate
6197 against the keyword’s specification (ticket #39).
6198
6199 • Fixed the extractor raising an exception when encountering an empty
6200 string msgid. It now emits a warning to stderr.
6201
6202 • Numerous Python message extractor fixes: it now handles nested func‐
6203 tion calls within a gettext function call correctly, uses the correct
6204 line number for multi-line function calls, and other small fixes
6205 (tickets ticket #38 and ticket #39).
6206
6207 • Improved support for detecting Python string formatting fields in
6208 message strings (ticket #57).
6209
6210 • CLDR upgraded to the 1.5 release.
6211
6212 • Improved timezone formatting.
6213
6214 • Implemented scientific number formatting.
6215
6216 • Added mechanism to lookup locales by alias, for cases where browsers
6217 insist on including only the language code in the Accept-Language
6218 header, and sometimes even the incorrect language code.
6219
6220 Version 0.8.1
6221 (released on July 2nd 2007)
6222
6223 • default_locale() would fail when the value of the LANGUAGE environ‐
6224 ment variable contained multiple language codes separated by colon,
6225 as is explicitly allowed by the GNU gettext tools. As the default_lo‐
6226 cale() function is called at the module level in some modules, this
6227 bug would completely break importing these modules on systems where
6228 LANGUAGE is set that way.
6229
6230 • The character set specified in PO template files is now respected
6231 when creating new catalog files based on that template. This allows
6232 the use of characters outside the ASCII range in POT files (ticket
6233 #17).
6234
6235 • The default ordering of messages in generated POT files, which is
6236 based on the order those messages are found when walking the source
6237 tree, is no longer subject to differences between platforms; direc‐
6238 tory and file names are now always sorted alphabetically.
6239
6240 • The Python message extractor now respects the special encoding com‐
6241 ment to be able to handle files containing non-ASCII characters (‐
6242 ticket #23).
6243
6244 • Added N_ (gettext noop) to the extractor’s default keywords.
6245
6246 • Made locale string parsing more robust, and also take the script part
6247 into account (ticket #27).
6248
6249 • Added a function to list all locales for which locale data is avail‐
6250 able.
6251
6252 • Added a command-line option to the pybabel command which prints out
6253 all available locales (ticket #24).
6254
6255 • The name of the command-line script has been changed from just babel
6256 to pybabel to avoid a conflict with the OpenBabel project (ticket
6257 #34).
6258
6259 Version 0.8
6260 (released on June 20th 2007)
6261
6262 • First public release
6263
6264 License
6265 Babel is licensed under a three clause BSD License. It basically
6266 means: do whatever you want with it as long as the copyright in Babel
6267 sticks around, the conditions are not modified and the disclaimer is
6268 present. Furthermore you must not use the names of the authors to pro‐
6269 mote derivatives of the software without written consent.
6270
6271 The full license text can be found below (Babel License).
6272
6273 Authors
6274 Babel is written and maintained by the Babel team and various contribu‐
6275 tors:
6276
6277 • Aarni Koskela
6278
6279 • Christopher Lenz
6280
6281 • Armin Ronacher
6282
6283 • Alex Morega
6284
6285 • Lasse Schuirmann
6286
6287 • Felix Schwarz
6288
6289 • Pedro Algarvio
6290
6291 • Jeroen Ruigrok van der Werven
6292
6293 • Philip Jenvey
6294
6295 • benselme
6296
6297 • Isaac Jurado
6298
6299 • Tobias Bieniek
6300
6301 • Erick Wilder
6302
6303 • Michael Birtwell
6304
6305 • Jonas Borgström
6306
6307 • Kevin Deldycke
6308
6309 • Jon Dufresne
6310
6311 • Ville Skyttä
6312
6313 • Jun Omae
6314
6315 • Hugo
6316
6317 • Heungsub Lee
6318
6319 • Jakob Schnitzer
6320
6321 • Sachin Paliwal
6322
6323 • Alex Willmer
6324
6325 • Daniel Neuhäuser
6326
6327 • Hugo van Kemenade
6328
6329 • Miro Hrončok
6330
6331 • Cédric Krier
6332
6333 • Luke Plant
6334
6335 • Jennifer Wang
6336
6337 • Lukas Balaga
6338
6339 • sudheesh001
6340
6341 • Niklas Hambüchen
6342
6343 • Changaco
6344
6345 • Xavier Fernandez
6346
6347 • KO. Mattsson
6348
6349 • Sébastien Diemer
6350
6351 • alexbodn@gmail.com
6352
6353 • saurabhiiit
6354
6355 • srisankethu
6356
6357 • Erik Romijn
6358
6359 • Lukas B
6360
6361 • Ryan J Ollos
6362
6363 • Arturas Moskvinas
6364
6365 • Leonardo Pistone
6366
6367 • Hyunjun Kim
6368
6369 • Eric L
6370
6371 • Jonah Lawrence
6372
6373 • Przemyslaw Wegrzyn
6374
6375 • Lukas Kahwe Smith
6376
6377 • Lukas Juhrich
6378
6379 • Nikita Sobolev
6380
6381 • Raphael Nestler
6382
6383 • Frank Harrison
6384
6385 • Nehal J Wani
6386
6387 • Mohamed Morsy
6388
6389 • Krzysztof Jagiełło
6390
6391 • Morgan Wahl
6392
6393 • farhan5900
6394
6395 • Sigurd Ljødal
6396
6397 • Andrii Oriekhov
6398
6399 • rachele-collin
6400
6401 • Lukas Winkler
6402
6403 • Juliette Monsel
6404
6405 • Álvaro Mondéjar Rubio
6406
6407 • ruro
6408
6409 • Alessio Bogon
6410
6411 • Nikiforov Konstantin
6412
6413 • Abdullah Javed Nesar
6414
6415 • Brad Martin
6416
6417 • Tyler Kennedy
6418
6419 • CyanNani123
6420
6421 • sebleblanc
6422
6423 • He Chen
6424
6425 • Steve (Gadget) Barnes
6426
6427 • Romuald Brunet
6428
6429 • Mario Frasca
6430
6431 • BT-sschmid
6432
6433 • Alberto Mardegan
6434
6435 • mondeja
6436
6437 • NotAFile
6438
6439 • Julien Palard
6440
6441 • Brian Cappello
6442
6443 • Serban Constantin
6444
6445 • Bryn Truscott
6446
6447 • Chris
6448
6449 • Charly C
6450
6451 • PTrottier
6452
6453 • xmo-odoo
6454
6455 • StevenJ
6456
6457 • Jungmo Ku
6458
6459 • Simeon Visser
6460
6461 • Narendra Vardi
6462
6463 • Stefane Fermigier
6464
6465 • Narayan Acharya
6466
6467 • François Magimel
6468
6469 • Wolfgang Doll
6470
6471 • Roy Williams
6472
6473 • Marc-André Dufresne
6474
6475 • Abhishek Tiwari
6476
6477 • David Baumgold
6478
6479 • Alex Kuzmenko
6480
6481 • Georg Schölly
6482
6483 • ldwoolley
6484
6485 • Rodrigo Ramírez Norambuena
6486
6487 • Jakub Wilk
6488
6489 • Roman Rader
6490
6491 • Max Shenfield
6492
6493 • Nicolas Grilly
6494
6495 • Kenny Root
6496
6497 • Adam Chainz
6498
6499 • Sébastien Fievet
6500
6501 • Anthony Sottile
6502
6503 • Yuriy Shatrov
6504
6505 • iamshubh22
6506
6507 • Sven Anderson
6508
6509 • Eoin Nugent
6510
6511 • Roman Imankulov
6512
6513 • David Stanek
6514
6515 • Roy Wellington Ⅳ
6516
6517 • Florian Schulze
6518
6519 • Todd M. Guerra
6520
6521 • Joseph Breihan
6522
6523 • Craig Loftus
6524
6525 • The Gitter Badger
6526
6527 • Régis Behmo
6528
6529 • Julen Ruiz Aizpuru
6530
6531 • astaric
6532
6533 • Felix Yan
6534
6535 • Philip_Tzou
6536
6537 • Jesús Espino
6538
6539 • Jeremy Weinstein
6540
6541 • James Page
6542
6543 • masklinn
6544
6545 • Sjoerd Langkemper
6546
6547 • Matt Iversen
6548
6549 • Alexander A. Dyshev
6550
6551 • Dirkjan Ochtman
6552
6553 • Nick Retallack
6554
6555 • Thomas Waldmann
6556
6557 • xen
6558
6559 Babel was previously developed under the Copyright of Edgewall Soft‐
6560 ware. The following copyright notice holds true for releases before
6561 2013: “Copyright (c) 2007 - 2011 by Edgewall Software”
6562
6563 In addition to the regular contributions Babel includes a fork of
6564 Lennart Regebro’s tzlocal that originally was licensed under the CC0
6565 license. The original copyright of that project is “Copyright 2013 by
6566 Lennart Regebro”.
6567
6568 General License Definitions
6569 The following section contains the full license texts for Babel and the
6570 documentation.
6571
6572 • “AUTHORS” hereby refers to all the authors listed in the Authors sec‐
6573 tion.
6574
6575 • The “Babel License” applies to all the sourcecode shipped as part of
6576 Babel (Babel itself as well as the examples and the unit tests) as
6577 well as documentation.
6578
6579 Babel License
6580 Copyright (c) 2013-2022 by the Babel Team, see AUTHORS for more infor‐
6581 mation.
6582
6583 Redistribution and use in source and binary forms, with or without mod‐
6584 ification, are permitted provided that the following conditions are
6585 met:
6586
6587 1. Redistributions of source code must retain the above copyright
6588 notice, this list of conditions and the following disclaimer.
6589
6590 2. Redistributions in binary form must reproduce the above copyright
6591 notice, this list of conditions and the following disclaimer in
6592 the documentation and/or other materials provided with the dis‐
6593 tribution.
6594
6595 3. Neither the name of the copyright holder nor the names of its
6596 contributors may be used to endorse or promote products derived
6597 from this software without specific prior written permission.
6598
6599 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS
6600 IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
6601 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC‐
6602 ULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
6603 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
6604 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
6605 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
6606 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
6607 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
6608 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
6609 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6610
6612 The Babel Team
6613
6615 2023, The Babel Team
6616
6617
6618
6619
66202.11 Jan 18, 2023 BABEL(1)