-# -*- coding: utf-8 -*-
"""
babel
~~~~~
-# -*- coding: utf-8 -*-
"""
babel.core
~~~~~~~~~~
self.identifier = identifier
-class Locale(object):
+class Locale:
"""Representation of a specific locale.
>>> locale = Locale('en', 'US')
-# -*- coding: utf-8 -*-
"""
babel.dates
~~~~~~~~~~~
:license: BSD, see LICENSE for more details.
"""
-from __future__ import division
import re
import warnings
)
-class TimezoneTransition(object):
+class TimezoneTransition:
"""A helper object that represents the return value from
:func:`get_next_timezone_transition`.
indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
indexes.sort()
- indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
+ indexes = {item[1]: idx for idx, item in enumerate(indexes)}
# FIXME: this currently only supports numbers, but should also support month
# names, both in the requested locale, and english
indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
indexes.sort()
- indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
+ indexes = {item[1]: idx for idx, item in enumerate(indexes)}
# TODO: support time zones
return time(hour, minute, second)
-class DateTimePattern(object):
+class DateTimePattern:
def __init__(self, pattern, format):
self.pattern = pattern
return self % DateTimeFormat(datetime, locale)
-class DateTimeFormat(object):
+class DateTimeFormat:
def __init__(self, value, locale):
assert isinstance(value, (date, datetime, time))
-# -- encoding: UTF-8 --
from babel.core import get_global
-# -*- coding: utf-8 -*-
"""
babel.lists
~~~~~~~~~~~
-# -*- coding: utf-8 -*-
"""
babel.localedata
~~~~~~~~~~~~~~~~
dict1[key] = val1
-class Alias(object):
+class Alias:
"""Representation of an alias in the locale data.
An alias is a value that refers to some other part of the locale data,
-# -*- coding: utf-8 -*-
"""
babel.localtime
~~~~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
-from __future__ import with_statement
import os
import re
import sys
tzpath = os.path.join(_root, filename)
if not os.path.exists(tzpath):
continue
- with open(tzpath, 'rt') as tzfile:
+ with open(tzpath) as tzfile:
for line in tzfile:
match = timezone_re.match(line)
if match is not None:
-# -*- coding: utf-8 -*-
"""
babel.messages
~~~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
"""
babel.messages.catalog
~~~~~~~~~~~~~~~~~~~~~~
return dt
-class Message(object):
+class Message:
"""Representation of a single message in a catalog."""
def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(),
#"""
-class Catalog(object):
+class Catalog:
"""Representation of a message catalog."""
def __init__(self, locale=None, domain=None, header_comment=DEFAULT_HEADER,
# Prepare for fuzzy matching
fuzzy_candidates = []
if not no_fuzzy_matching:
- fuzzy_candidates = dict([
- (self._key_for(msgid), messages[msgid].context)
+ fuzzy_candidates = {
+ self._key_for(msgid): messages[msgid].context
for msgid in messages if msgid and messages[msgid].string
- ])
+ }
fuzzy_matches = set()
def _merge(message, oldkey, newkey):
-# -*- coding: utf-8 -*-
"""
babel.messages.checkers
~~~~~~~~~~~~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
"""
babel.messages.extract
~~~~~~~~~~~~~~~~~~~~~~
for filename in filenames:
filepath = os.path.join(root, filename).replace(os.sep, '/')
- for message_tuple in check_and_call_extract_file(
+ yield from check_and_call_extract_file(
filepath,
method_map,
options_map,
comment_tags,
strip_comment_tags,
dirpath=absname,
- ):
- yield message_tuple
+ )
def check_and_call_extract_file(filepath, method_map, options_map,
-# -*- coding: utf-8 -*-
"""
babel.messages.frontend
~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013-2022 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
-from __future__ import print_function
import fnmatch
import logging
return
-class CommandLineInterface(object):
+class CommandLineInterface:
"""Command-line interface.
This class provides a simple command-line interface to the message
self._configure_logging(options.loglevel)
if options.list_locales:
identifiers = localedata.locale_identifiers()
- longest = max([len(identifier) for identifier in identifiers])
+ longest = max(len(identifier) for identifier in identifiers)
identifiers.sort()
format = u'%%-%ds %%s' % (longest + 1)
for identifier in identifiers:
def _help(self):
print(self.parser.format_help())
print("commands:")
- longest = max([len(command) for command in self.commands])
+ longest = max(len(command) for command in self.commands)
format = " %%-%ds %%s" % max(8, longest + 1)
commands = sorted(self.commands.items())
for name, description in commands:
if section == 'extractors':
extractors = dict(parser.items(section))
else:
- method, pattern = [part.strip() for part in section.split(':', 1)]
+ method, pattern = (part.strip() for part in section.split(':', 1))
method_map.append((pattern, method))
options_map[pattern] = dict(parser.items(section))
-# -*- coding: utf-8 -*-
"""
babel.messages.jslexer
~~~~~~~~~~~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
"""
babel.messages.mofile
~~~~~~~~~~~~~~~~~~~~~
version, msgcount, origidx, transidx = unpack('>4I', buf[4:20])
ii = '>II'
else:
- raise IOError(0, 'Bad magic number', filename)
+ raise OSError(0, 'Bad magic number', filename)
# Now put all messages from the .mo file buffer into the catalog
# dictionary
msg = buf[moff:mend]
tmsg = buf[toff:tend]
else:
- raise IOError(0, 'File is corrupt', filename)
+ raise OSError(0, 'File is corrupt', filename)
# See if we're looking at GNU .mo conventions for metadata
if mlen == 0:
-# -*- coding: utf-8 -*-
"""
babel.messages.plurals
~~~~~~~~~~~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
"""
babel.messages.pofile
~~~~~~~~~~~~~~~~~~~~~
:license: BSD, see LICENSE for more details.
"""
-from __future__ import print_function
import os
import re
class PoFileError(Exception):
"""Exception thrown by PoParser when an invalid po file is encountered."""
def __init__(self, message, catalog, line, lineno):
- super(PoFileError, self).__init__('{message} on {lineno}'.format(message=message, lineno=lineno))
+ super().__init__(f'{message} on {lineno}')
self.catalog = catalog
self.line = line
self.lineno = lineno
-class _NormalizedString(object):
+class _NormalizedString:
def __init__(self, *args):
self._strs = []
-class PoFileParser(object):
+class PoFileParser:
"""Support class to read messages from a ``gettext`` PO (portable object) file
and add them to a `Catalog`
"""
self.translations.sort()
if len(self.messages) > 1:
- msgid = tuple([m.denormalize() for m in self.messages])
+ msgid = tuple(m.denormalize() for m in self.messages)
else:
msgid = self.messages[0].denormalize()
if isinstance(msgid, (list, tuple)):
-# -*- coding: utf-8 -*-
"""
babel.numbers
~~~~~~~~~~~~~
"""Exception raised when a string cannot be parsed into a number."""
def __init__(self, message, suggestions=None):
- super(NumberFormatError, self).__init__(message)
+ super().__init__(message)
#: a list of properly formatted numbers derived from the invalid input
self.suggestions = suggestions
exp_prec, exp_plus)
-class NumberPattern(object):
+class NumberPattern:
def __init__(self, pattern, prefix, suffix, grouping,
int_prec, frac_prec, exp_prec, exp_plus):
-# -*- coding: utf-8 -*-
"""
babel.numbers
~~~~~~~~~~~~~
return n, i, v, w, f, t, c, e
-class PluralRule(object):
+class PluralRule:
"""Represents a set of language pluralization rules. The constructor
accepts a list of (tag, expr) tuples or a dict of `CLDR rules`_. The
resulting object is callable and accepts one parameter with a positive or
{'one': 'n is 1'}
"""
_compile = _UnicodeCompiler().compile
- return dict([(tag, _compile(ast)) for tag, ast in self.abstract])
+ return {tag: _compile(ast) for tag, ast in self.abstract}
- tags = property(lambda x: frozenset([i[0] for i in x.abstract]), doc="""
+ tags = property(lambda x: frozenset(i[0] for i in x.abstract), doc="""
A set of explicitly defined tags in this rule. The implicit default
``'other'`` rules is not part of this set unless there is an explicit
rule for it.""")
return 'not', (rv,)
-class _Parser(object):
+class _Parser:
"""Internal parser. This class can translate a single rule into an abstract
tree of tuples. It implements the following grammar::
compile_zero = lambda x: '0'
-class _Compiler(object):
+class _Compiler:
"""The compilers are able to transform the expressions into multiple
output formats.
"""
-# -*- coding: utf-8 -*-
"""
babel.support
~~~~~~~~~~~~~
format_percent, format_scientific
-class Format(object):
+class Format:
"""Wrapper class providing the various date and number formatting functions
bound to a specific locale and time-zone.
return format_scientific(number, locale=self.locale)
-class LazyProxy(object):
+class LazyProxy:
"""Class for proxy objects that delegate to a specified function to evaluate
the actual object.
)
-class NullTranslations(gettext.NullTranslations, object):
+class NullTranslations(gettext.NullTranslations):
DEFAULT_DOMAIN = None
# some *gettext methods (including '.gettext()') rely on the attributes.
self._catalog = {}
self.plural = lambda n: int(n != 1)
- super(NullTranslations, self).__init__(fp=fp)
+ super().__init__(fp=fp)
self.files = list(filter(None, [getattr(fp, 'name', None)]))
self.domain = self.DEFAULT_DOMAIN
self._domains = {}
:param fp: the file-like object the translation should be read from
:param domain: the message domain (default: 'messages')
"""
- super(Translations, self).__init__(fp=fp)
+ super().__init__(fp=fp)
self.domain = domain or self.DEFAULT_DOMAIN
ugettext = gettext.GNUTranslations.gettext
-# -- encoding: UTF-8 --
-
from babel.core import Locale
from babel.numbers import format_decimal, LC_NUMERIC
-# -*- coding: utf-8 -*-
"""
babel.util
~~~~~~~~~~
-# -*- coding: utf-8 -*-
#
# Babel documentation build configuration file, created by
# sphinx-quickstart on Wed Jul 3 17:53:01 2013.
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
all_currencies[cur_code].add(region_code)
region_currencies.sort(key=_currency_sort_key)
territory_currencies[region_code] = region_currencies
- global_data['all_currencies'] = dict([
- (currency, tuple(sorted(regions))) for currency, regions in all_currencies.items()])
+ global_data['all_currencies'] = {
+ currency: tuple(sorted(regions)) for currency, regions in all_currencies.items()}
# Explicit parent locales
for paternity in sup.findall('.//parentLocales/parentLocale'):
region_items = sorted(regions.items())
for group, territory_list in region_items:
for territory in territory_list:
- containers = territory_containment.setdefault(territory, set([]))
+ containers = territory_containment.setdefault(territory, set())
if group in territory_containment:
containers |= territory_containment[group]
containers.add(group)
type = rule.attrib["type"]
if type in ("am", "pm"): # These fixed periods are handled separately by `get_period_id`
continue
- rule = _compact_dict(dict(
- (key, _time_to_seconds_past_midnight(rule.attrib.get(key)))
+ rule = _compact_dict({
+ key: _time_to_seconds_past_midnight(rule.attrib.get(key))
for key in ("after", "at", "before", "from", "to")
- ))
+ })
for locale in locales:
dest_list = day_periods.setdefault(locale, {}).setdefault(ruleset_type, {}).setdefault(type, [])
dest_list.append(rule)
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
"""
make-release
~~~~~~~~~~~~
-# -*- coding: utf-8 -*-
-
import subprocess
import sys
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
'-o', po_file,
'-i', tmpl_file
])
- with open(po_file, "r") as infp:
+ with open(po_file) as infp:
catalog = read_po(infp)
assert len(catalog) == 3
'-o', po_file,
'-i', tmpl_file])
- with open(po_file, "r") as infp:
+ with open(po_file) as infp:
catalog = read_po(infp)
assert len(catalog) == 4 # Catalog was updated
'-o', po_file,
'-i', tmpl_file])
- with open(po_file, "r") as infp:
+ with open(po_file) as infp:
catalog = read_po(infp)
assert len(catalog) == 3
'-o', po_file,
'-i', tmpl_file])
- with open(po_file, "r") as infp:
+ with open(po_file) as infp:
catalog = read_po(infp)
assert len(catalog) == 4 # Catalog was updated
-# -- encoding: UTF-8 --
from io import BytesIO
import pytest
from babel.messages import extract
-# -*- coding: utf-8 -*-
-
from babel.messages import jslexer
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
import datetime
from babel import dates
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -- encoding: UTF-8 --
from datetime import time
import babel.dates as dates
-# -- encoding: UTF-8 --
from babel.languages import get_official_languages, get_territory_language_info
-# coding=utf-8
import pytest
from babel import lists
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -- encoding: UTF-8 --
"""
These tests do not verify any results and should not be run when
looking at improving test coverage. They just verify that basic
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.
-# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2022 the Babel team
# All rights reserved.