module documentation

Basic infrastructure for extracting localizable messages from source files.

This module defines an extensible system for collecting localizable message strings from a variety of sources. A native extractor for Python source files is builtin, extractors for other sources can be added using very simple plugins.

The main entry points into the extraction functionality are the functions extract_from_dir and extract_from_file.

Unknown Field: copyright
  1. 2013-2021 by the Babel Team.
Unknown Field: license
BSD, see LICENSE for more details.
Function extract Extract messages from the given file-like object using the specified extraction method.
Function extract​_from​_dir Extract messages from any source files found in the given directory.
Function extract​_from​_file Extract messages from a specific file.
Function extract​_javascript Extract messages from JavaScript source code.
Function extract​_nothing Pseudo extractor that does not actually extract anything, but simply returns an empty list.
Function extract​_python Extract messages from Python source code.
Constant DEFAULT​_KEYWORDS Undocumented
Constant DEFAULT​_MAPPING Undocumented
Constant GROUP​_NAME Undocumented
Variable empty​_msgid​_warning Undocumented
Function ​_strip​_comment​_tags Helper function for extract that strips comment tags from strings in a list of comment lines. This functions operates in-place.
Function check​_and​_call​_extract​_file Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file.
def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(), options=None, strip_comment_tags=False):

Extract messages from the given file-like object using the specified extraction method.

This function returns tuples of the form (lineno, message, comments, context).

The implementation dispatches the actual extraction to plugins, based on the value of the method parameter.

>>> source = b'''# foo module
... def run(argv):
...    print(_('Hello, world!'))
... '''
>>> from babel._compat import BytesIO
>>> for message in extract('python', BytesIO(source)):
...     print(message)
(3, u'Hello, world!', [], None)
Parameters
methodan extraction method (a callable), or a string specifying the extraction method (.e.g. "python"); if this is a simple name, the extraction function will be looked up by entry point; if it is an explicit reference to a function (of the form package.module:funcname or package.module.funcname), the corresponding function will be imported and used
fileobjthe file-like object the messages should be extracted from
keywordsa dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
comment​_tagsa list of translator tags to search for and include in the results
optionsa dictionary of additional options (optional)
strip​_comment​_tagsa flag that if set to True causes all comment tags to be removed from the collected comments.
Returns
Iterable[tuple[int, str|tuple[str], list[str], str|None]iterable of tuples of the form (lineno, message, comments, context)
Raises
ValueErrorif the extraction method is not registered
def extract_from_dir(dirname=None, method_map=DEFAULT_MAPPING, options_map=None, keywords=DEFAULT_KEYWORDS, comment_tags=(), callback=None, strip_comment_tags=False):

Extract messages from any source files found in the given directory.

This function generates tuples of the form (filename, lineno, message, comments, context).

Which extraction method is used per file is determined by the method_map parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping:

>>> method_map = [
...     ('**.py', 'python')
... ]

This basically says that files with the filename extension ".py" at any level inside the directory should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the pathmatch function for details on the pattern syntax.

The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory:

>>> method_map = [
...     ('**/templates/**.*', 'genshi'),
...     ('**.py', 'python')
... ]

The dictionary provided by the optional options_map parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings).

The glob patterns of the options_map do not necessarily need to be the same as those used in the method mapping. For example, while all files in the templates folders in an application may be Genshi applications, the options for those files may differ based on extension:

>>> options_map = {
...     '**/templates/**.txt': {
...         'template_class': 'genshi.template:TextTemplate',
...         'encoding': 'latin-1'
...     },
...     '**/templates/**.html': {
...         'include_attrs': ''
...     }
... }
Parameters
dirnamethe path to the directory to extract messages from. If not given the current working directory is used.
method​_mapa list of (pattern, method) tuples that maps of extraction method names to extended glob patterns
options​_mapa dictionary of additional options (optional)
keywordsa dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
comment​_tagsa list of tags of translator comments to search for and include in the results
callbacka function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order
strip​_comment​_tagsa flag that if set to True causes all comment tags to be removed from the collected comments.
See Also
pathmatch
def extract_from_file(method, filename, keywords=DEFAULT_KEYWORDS, comment_tags=(), options=None, strip_comment_tags=False):

Extract messages from a specific file.

This function returns a list of tuples of the form (lineno, message, comments, context).

Parameters
methoda string specifying the extraction method (.e.g. "python")
filenamethe path to the file to extract messages from
keywordsa dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
comment​_tagsa list of translator tags to search for and include in the results
optionsa dictionary of additional options (optional)
strip​_comment​_tagsa flag that if set to True causes all comment tags to be removed from the collected comments.
Returns
list[tuple[int, str|tuple[str], list[str], str|None]list of tuples of the form (lineno, message, comments, context)
def extract_javascript(fileobj, keywords, comment_tags, options):
Extract messages from JavaScript source code.
Parameters
fileobjthe seekable, file-like object the messages should be extracted from
keywordsa list of keywords (i.e. function names) that should be recognized as translation functions
comment​_tagsa list of translator tags to search for and include in the results
options

a dictionary of additional options (optional) Supported options are: * jsx -- set to false to disable JSX/E4X support. * template_string -- set to false to disable ES6

template string support.
def extract_nothing(fileobj, keywords, comment_tags, options):
Pseudo extractor that does not actually extract anything, but simply returns an empty list.
def extract_python(fileobj, keywords, comment_tags, options):

Extract messages from Python source code.

It returns an iterator yielding tuples in the following form (lineno, funcname, message, comments).

Parameters
fileobjthe seekable, file-like object the messages should be extracted from
keywordsa list of keywords (i.e. function names) that should be recognized as translation functions
comment​_tagsa list of translator tags to search for and include in the results
optionsa dictionary of additional options (optional)
Returns
iteratorUndocumented
DEFAULT_KEYWORDS: dict =

Undocumented

Value
{'_': None,
 'gettext': None,
 'ngettext': (1, 2),
 'ugettext': None,
 'ungettext': (1, 2),
 'dgettext': (2),
 'dngettext': (2, 3),
...
DEFAULT_MAPPING: list =

Undocumented

Value
[('**.py', 'python')]
GROUP_NAME: str =

Undocumented

Value
'babel.extractors'
empty_msgid_warning: str =

Undocumented

def _strip_comment_tags(comments, tags):
Helper function for extract that strips comment tags from strings in a list of comment lines. This functions operates in-place.
def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None):

Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file.

Note that the extraction method mappings are based relative to dirpath. So, given an absolute path to a file filepath, we want to check using just the relative path from dirpath to filepath.

Yields 5-tuples (filename, lineno, messages, comments, context).

Parameters
filepathAn absolute path to a file that exists.
method​_mapa list of (pattern, method) tuples that maps of extraction method names to extended glob patterns
options​_mapa dictionary of additional options (optional)
callbacka function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order
keywordsa dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
comment​_tagsa list of tags of translator comments to search for and include in the results
strip​_comment​_tagsa flag that if set to True causes all comment tags to be removed from the collected comments.
dirpaththe path to the directory to extract messages from.
Returns
Iterable[tuple[str, int, str|tuple[str], list[str], str|None]iterable of 5-tuples (filename, lineno, messages, comments, context)