Messages and Catalogs

This module provides a basic interface to hold catalog and message information. It’s generally used to modify a gettext catalog but it is not being used to actually use the translations.

Catalogs

class babel.messages.catalog.Catalog(locale: str | babel.core.Locale | None = None, domain: str | None = None, header_comment: str | None = '# Translations template for PROJECT.\n# Copyright (C) YEAR ORGANIZATION\n# This file is distributed under the same license as the PROJECT project.\n# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n#', project: str | None = None, version: str | None = None, copyright_holder: str | None = None, msgid_bugs_address: str | None = None, creation_date: datetime.datetime | str | None = None, revision_date: datetime.datetime | datetime.time | float | str | None = None, last_translator: str | None = None, language_team: str | None = None, charset: str | None = None, fuzzy: bool = True)

Representation of a message catalog.

__iter__() Iterator[Message]

Iterates through all the entries in the catalog, in the order they were added, yielding a Message object for every entry.

Return type:

iterator

add(id: _MessageID, string: _MessageID | None = None, locations: Iterable[tuple[str, int]] = (), flags: Iterable[str] = (), auto_comments: Iterable[str] = (), user_comments: Iterable[str] = (), previous_id: _MessageID = (), lineno: int | None = None, context: str | None = None) Message

Add or update the message with the specified ID.

>>> catalog = Catalog()
>>> catalog.add(u'foo')
<Message ...>
>>> catalog[u'foo']
<Message u'foo' (flags: [])>

This method simply constructs a Message object with the given arguments and invokes __setitem__ with that object.

Parameters:
  • id – the message ID, or a (singular, plural) tuple for pluralizable messages

  • string – the translated message string, or a (singular, plural) tuple for pluralizable messages

  • locations – a sequence of (filename, lineno) tuples

  • flags – a set or sequence of flags

  • auto_comments – a sequence of automatic comments

  • user_comments – a sequence of user comments

  • previous_id – the previous message ID, or a (singular, plural) tuple for pluralizable messages

  • lineno – the line number on which the msgid line was found in the PO file, if any

  • context – the message context

check() Iterable[tuple[babel.messages.catalog.Message, list[babel.messages.catalog.TranslationError]]]

Run various validation checks on the translations in the catalog.

For every message which fails validation, this method yield a (message, errors) tuple, where message is the Message object and errors is a sequence of TranslationError objects.

Return type:

generator of (message, errors)

delete(id: _MessageID, context: str | None = None) None

Delete the message with the specified ID and context.

Parameters:
  • id – the message ID

  • context – the message context, or None for no context

get(id: _MessageID, context: str | None = None) Message | None

Return the message with the specified ID and context.

Parameters:
  • id – the message ID

  • context – the message context, or None for no context

property header_comment: str

The header comment for the catalog.

>>> catalog = Catalog(project='Foobar', version='1.0',
...                   copyright_holder='Foo Company')
>>> print(catalog.header_comment) 
# Translations template for Foobar.
# Copyright (C) ... Foo Company
# This file is distributed under the same license as the Foobar project.
# FIRST AUTHOR <EMAIL@ADDRESS>, ....
#

The header can also be set from a string. Any known upper-case variables will be replaced when the header is retrieved again:

>>> catalog = Catalog(project='Foobar', version='1.0',
...                   copyright_holder='Foo Company')
>>> catalog.header_comment = '''\
... # The POT for my really cool PROJECT project.
... # Copyright (C) 1990-2003 ORGANIZATION
... # This file is distributed under the same license as the PROJECT
... # project.
... #'''
>>> print(catalog.header_comment)
# The POT for my really cool Foobar project.
# Copyright (C) 1990-2003 Foo Company
# This file is distributed under the same license as the Foobar
# project.
#
Type:

unicode

is_identical(other: Catalog) bool

Checks if catalogs are identical, taking into account messages and headers.

language_team

Name and email address of the language team.

last_translator

Name and email address of the last translator.

property mime_headers: list[tuple[str, str]]

The MIME headers of the catalog, used for the special msgid "" entry.

The behavior of this property changes slightly depending on whether a locale is set or not, the latter indicating that the catalog is actually a template for actual translations.

Here’s an example of the output for such a catalog template:

>>> from babel.dates import UTC
>>> from datetime import datetime
>>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
>>> catalog = Catalog(project='Foobar', version='1.0',
...                   creation_date=created)
>>> for name, value in catalog.mime_headers:
...     print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
Last-Translator: FULL NAME <EMAIL@ADDRESS>
Language-Team: LANGUAGE <LL@li.org>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...

And here’s an example of the output when the locale is set:

>>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
>>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
...                   creation_date=created, revision_date=revised,
...                   last_translator='John Doe <jd@example.com>',
...                   language_team='de_DE <de@example.com>')
>>> for name, value in catalog.mime_headers:
...     print('%s: %s' % (name, value))
Project-Id-Version: Foobar 1.0
Report-Msgid-Bugs-To: EMAIL@ADDRESS
POT-Creation-Date: 1990-04-01 15:30+0000
PO-Revision-Date: 1990-08-03 12:00+0000
Last-Translator: John Doe <jd@example.com>
Language: de_DE
Language-Team: de_DE <de@example.com>
Plural-Forms: nplurals=2; plural=(n != 1);
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Generated-By: Babel ...
Type:

list

property num_plurals: int

The number of plurals used by the catalog or locale.

>>> Catalog(locale='en').num_plurals
2
>>> Catalog(locale='ga').num_plurals
5
Type:

int

property plural_expr: str

The plural expression used by the catalog or locale.

>>> Catalog(locale='en').plural_expr
'(n != 1)'
>>> Catalog(locale='ga').plural_expr
'(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)'
>>> Catalog(locale='ding').plural_expr  # unknown locale
'(n != 1)'
Type:

str

property plural_forms: str

Return the plural forms declaration for the locale.

>>> Catalog(locale='en').plural_forms
'nplurals=2; plural=(n != 1);'
>>> Catalog(locale='pt_BR').plural_forms
'nplurals=2; plural=(n > 1);'
Type:

str

update(template: Catalog, no_fuzzy_matching: bool = False, update_header_comment: bool = False, keep_user_comments: bool = True, update_creation_date: bool = True) None

Update the catalog based on the given template catalog.

>>> from babel.messages import Catalog
>>> template = Catalog()
>>> template.add('green', locations=[('main.py', 99)])
<Message ...>
>>> template.add('blue', locations=[('main.py', 100)])
<Message ...>
>>> template.add(('salad', 'salads'), locations=[('util.py', 42)])
<Message ...>
>>> catalog = Catalog(locale='de_DE')
>>> catalog.add('blue', u'blau', locations=[('main.py', 98)])
<Message ...>
>>> catalog.add('head', u'Kopf', locations=[('util.py', 33)])
<Message ...>
>>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'),
...             locations=[('util.py', 38)])
<Message ...>
>>> catalog.update(template)
>>> len(catalog)
3
>>> msg1 = catalog['green']
>>> msg1.string
>>> msg1.locations
[('main.py', 99)]
>>> msg2 = catalog['blue']
>>> msg2.string
u'blau'
>>> msg2.locations
[('main.py', 100)]
>>> msg3 = catalog['salad']
>>> msg3.string
(u'Salat', u'Salate')
>>> msg3.locations
[('util.py', 42)]

Messages that are in the catalog but not in the template are removed from the main collection, but can still be accessed via the obsolete member:

>>> 'head' in catalog
False
>>> list(catalog.obsolete.values())
[<Message 'head' (flags: [])>]
Parameters:
  • template – the reference catalog, usually read from a POT file

  • no_fuzzy_matching – whether to use fuzzy matching of message IDs

Messages

class babel.messages.catalog.Message(id: _MessageID, string: _MessageID | None = '', locations: Iterable[tuple[str, int]] = (), flags: Iterable[str] = (), auto_comments: Iterable[str] = (), user_comments: Iterable[str] = (), previous_id: _MessageID = (), lineno: int | None = None, context: str | None = None)

Representation of a single message in a catalog.

check(catalog: babel.messages.catalog.Catalog | None = None) list[babel.messages.catalog.TranslationError]

Run various validation checks on the message. Some validations are only performed if the catalog is provided. This method returns a sequence of TranslationError objects.

Return type:

iterator

Parameters:

catalog – A catalog instance that is passed to the checkers

See:

Catalog.check for a way to perform checks for all messages in a catalog.

property fuzzy: bool

Whether the translation is fuzzy.

>>> Message('foo').fuzzy
False
>>> msg = Message('foo', 'foo', flags=['fuzzy'])
>>> msg.fuzzy
True
>>> msg
<Message 'foo' (flags: ['fuzzy'])>
Type:

bool

is_identical(other: Message) bool

Checks whether messages are identical, taking into account all properties.

property pluralizable: bool

Whether the message is plurizable.

>>> Message('foo').pluralizable
False
>>> Message(('foo', 'bar')).pluralizable
True
Type:

bool

property python_format: bool

Whether the message contains Python-style parameters.

>>> Message('foo %(name)s bar').python_format
True
>>> Message(('foo %(name)s', 'foo %(name)s')).python_format
True
Type:

bool

Exceptions

exception babel.messages.catalog.TranslationError

Exception thrown by translation checkers when invalid message translations are encountered.