From 8a1eef5ca664992137115f5613f1d0e1500fdf6a Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Mon, 27 Nov 2023 15:18:54 +0200 Subject: [PATCH] Enforce trailing commas (enable Ruff COM rule and autofix) (#1045) --- babel/core.py | 4 +-- babel/dates.py | 8 ++--- babel/lists.py | 2 +- babel/localtime/_helpers.py | 2 +- babel/messages/catalog.py | 2 +- babel/messages/checkers.py | 4 +-- babel/messages/extract.py | 10 +++--- babel/messages/frontend.py | 30 ++++++++--------- babel/messages/jslexer.py | 4 +-- babel/messages/mofile.py | 2 +- babel/messages/plurals.py | 2 +- babel/messages/pofile.py | 4 +-- babel/messages/setuptools_frontend.py | 2 +- babel/numbers.py | 4 +-- babel/plural.py | 2 +- babel/support.py | 4 +-- babel/units.py | 2 +- babel/util.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 1 + scripts/import_cldr.py | 32 +++++++++---------- setup.py | 2 +- tests/messages/test_extract.py | 2 +- tests/messages/test_frontend.py | 16 +++++----- tests/messages/test_js_extract.py | 14 ++++---- tests/messages/test_jslexer.py | 6 ++-- tests/messages/test_pofile.py | 4 +-- tests/test_dates.py | 4 +-- tests/test_localedata.py | 4 +-- tests/test_numbers.py | 2 +- tests/test_plural.py | 46 ++++++++++++++++++++++----- 31 files changed, 128 insertions(+), 97 deletions(-) diff --git a/babel/core.py b/babel/core.py index ef0d16a1d..782c8f26a 100644 --- a/babel/core.py +++ b/babel/core.py @@ -111,7 +111,7 @@ def get_global(key: _GLOBAL_KEY) -> Mapping[str, Any]: 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', - 'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA' + 'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA', } @@ -1149,7 +1149,7 @@ def negotiate_locale(preferred: Iterable[str], available: Iterable[str], sep: st def parse_locale( identifier: str, - sep: str = '_' + sep: str = '_', ) -> tuple[str, str | None, str | None, str | None] | tuple[str, str | None, str | None, str | None, str | None]: """Parse a locale identifier into a tuple of the form ``(language, territory, script, variant, modifier)``. diff --git a/babel/dates.py b/babel/dates.py index ddc8e7105..40d950983 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -521,7 +521,7 @@ def get_timezone_location( return city_name return region_format % (fallback_format % { '0': city_name, - '1': territory_name + '1': territory_name, }) @@ -852,7 +852,7 @@ def format_skeleton( ('day', 3600 * 24), ('hour', 3600), ('minute', 60), - ('second', 1) + ('second', 1), ) @@ -1324,7 +1324,7 @@ def __init__( self, value: datetime.date | datetime.time, locale: Locale | str, - reference_date: datetime.date | None = None + reference_date: datetime.date | None = None, ) -> None: assert isinstance(value, (datetime.date, datetime.datetime, datetime.time)) if isinstance(value, (datetime.datetime, datetime.time)) and value.tzinfo is None: @@ -1663,7 +1663,7 @@ def get_week_number(self, day_of_period: int, day_of_week: int | None = None) -> 'm': [1, 2], # minute 's': [1, 2], 'S': None, 'A': None, # second 'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4, 5], 'O': [1, 4], 'v': [1, 4], # zone - 'V': [1, 2, 3, 4], 'x': [1, 2, 3, 4, 5], 'X': [1, 2, 3, 4, 5] # zone + 'V': [1, 2, 3, 4], 'x': [1, 2, 3, 4, 5], 'X': [1, 2, 3, 4, 5], # zone } #: The pattern characters declared in the Date Field Symbol Table diff --git a/babel/lists.py b/babel/lists.py index 5c435dd63..a8471fd1e 100644 --- a/babel/lists.py +++ b/babel/lists.py @@ -79,7 +79,7 @@ def format_list(lst: Sequence[str], if style not in locale.list_patterns: raise ValueError( f'Locale {locale} does not support list formatting style {style!r} ' - f'(supported are {sorted(locale.list_patterns)})' + f'(supported are {sorted(locale.list_patterns)})', ) patterns = locale.list_patterns[style] diff --git a/babel/localtime/_helpers.py b/babel/localtime/_helpers.py index 159f9a569..f27b31522 100644 --- a/babel/localtime/_helpers.py +++ b/babel/localtime/_helpers.py @@ -30,7 +30,7 @@ def _get_tzinfo_or_raise(tzenv: str): if tzinfo is None: raise LookupError( f"Can not find timezone {tzenv}. \n" - "Timezone names are generally in the form `Continent/City`." + "Timezone names are generally in the form `Continent/City`.", ) return tzinfo diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py index 8faf046d3..41adfaeee 100644 --- a/babel/messages/catalog.py +++ b/babel/messages/catalog.py @@ -861,7 +861,7 @@ def _merge(message: Message, oldkey: tuple[str, str] | str, newkey: tuple[str, s if not isinstance(message.string, (list, tuple)): fuzzy = True message.string = tuple( - [message.string] + ([''] * (len(message.id) - 1)) + [message.string] + ([''] * (len(message.id) - 1)), ) elif len(message.string) != self.num_plurals: fuzzy = True diff --git a/babel/messages/checkers.py b/babel/messages/checkers.py index f4070e56d..e5448e06b 100644 --- a/babel/messages/checkers.py +++ b/babel/messages/checkers.py @@ -19,7 +19,7 @@ _string_format_compatibilities = [ {'i', 'd', 'u'}, {'x', 'X'}, - {'f', 'F', 'g', 'G'} + {'f', 'F', 'g', 'G'}, ] @@ -150,7 +150,7 @@ def _check_positional(results: list[tuple[str, str]]) -> bool: elif not _compatible(typechar, type_map[name]): raise TranslationError( f'incompatible format for placeholder {name!r}: ' - f'{typechar!r} and {type_map[name]!r} are not compatible' + f'{typechar!r} and {type_map[name]!r} are not compatible', ) diff --git a/babel/messages/extract.py b/babel/messages/extract.py index a5b6eab07..b13f1a9a6 100644 --- a/babel/messages/extract.py +++ b/babel/messages/extract.py @@ -86,7 +86,7 @@ def tell(self) -> int: ... 'dngettext': (2, 3), 'N_': None, 'pgettext': ((1, 'c'), 2), - 'npgettext': ((1, 'c'), 2, 3) + 'npgettext': ((1, 'c'), 2, 3), } DEFAULT_MAPPING: list[tuple[str, str]] = [('**.py', 'python')] @@ -281,7 +281,7 @@ def check_and_call_extract_file( keywords=keywords, comment_tags=comment_tags, options=options, - strip_comment_tags=strip_comment_tags + strip_comment_tags=strip_comment_tags, ): yield (filename, *message_tuple) @@ -352,7 +352,7 @@ def _match_messages_against_spec(lineno: int, messages: list[str|None], comments filename = (getattr(fileobj, "name", None) or "(unknown)") sys.stderr.write( f"{filename}:{lineno}: warning: Empty msgid. It is reserved by GNU gettext: gettext(\"\") " - f"returns the header entry with meta information, not the empty string.\n" + f"returns the header entry with meta information, not the empty string.\n", ) return @@ -437,7 +437,7 @@ def extract( builtin = { 'ignore': extract_nothing, 'python': extract_python, - 'javascript': extract_javascript + 'javascript': extract_javascript, } func = builtin.get(method) @@ -690,7 +690,7 @@ def extract_javascript( jsx=options.get("jsx", True), template_string=options.get("template_string", True), dotted=dotted, - lineno=lineno + lineno=lineno, ): if ( # Turn keyword`foo` expressions into keyword("foo") calls: funcname and # have a keyword... diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 4d61f0163..5cdade9f0 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -166,7 +166,7 @@ class CompileCatalog(CommandMixin): ('use-fuzzy', 'f', 'also include fuzzy translations'), ('statistics', None, - 'print statistics about translations') + 'print statistics about translations'), ] boolean_options = ['use-fuzzy', 'statistics'] @@ -246,7 +246,7 @@ def _run_domain(self, domain): percentage = translated * 100 // len(catalog) self.log.info( '%d of %d messages (%d%%) translated in %s', - translated, len(catalog), percentage, po_file + translated, len(catalog), percentage, po_file, ) if catalog.fuzzy and not self.use_fuzzy: @@ -257,7 +257,7 @@ def _run_domain(self, domain): for message, errors in catalog_errors: for error in errors: self.log.error( - 'error: %s:%d: %s', po_file, message.lineno, error + 'error: %s:%d: %s', po_file, message.lineno, error, ) self.log.info('compiling catalog %s to %s', po_file, mo_file) @@ -342,7 +342,7 @@ class ExtractMessages(CommandMixin): ] boolean_options = [ 'no-default-keywords', 'no-location', 'omit-header', 'no-wrap', - 'sort-output', 'sort-by-file', 'strip-comments' + 'sort-output', 'sort-by-file', 'strip-comments', ] as_args = 'input-paths' multiple_value_options = ( @@ -357,7 +357,7 @@ class ExtractMessages(CommandMixin): 'strip-comments': ('--strip-comment-tags',), } option_choices = { - 'add-location': ('full', 'file', 'never',), + 'add-location': ('full', 'file', 'never'), } def initialize_options(self): @@ -391,7 +391,7 @@ def finalize_options(self): self.input_paths = self.input_dirs else: raise OptionError( - 'input-dirs and input-paths are mutually exclusive' + 'input-dirs and input-paths are mutually exclusive', ) keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy() @@ -402,14 +402,14 @@ def finalize_options(self): if not self.keywords: raise OptionError( - 'you must specify new keywords if you disable the default ones' + 'you must specify new keywords if you disable the default ones', ) if not self.output_file: raise OptionError('no output file specified') if self.no_wrap and self.width: raise OptionError( - "'--no-wrap' and '--width' are mutually exclusive" + "'--no-wrap' and '--width' are mutually exclusive", ) if not self.no_wrap and not self.width: self.width = 76 @@ -418,7 +418,7 @@ def finalize_options(self): if self.sort_output and self.sort_by_file: raise OptionError( - "'--sort-output' and '--sort-by-file' are mutually exclusive" + "'--sort-output' and '--sort-by-file' are mutually exclusive", ) if self.input_paths: @@ -497,7 +497,7 @@ def run(self): extracted = check_and_call_extract_file( path, method_map, options_map, callback, self.keywords, self.add_comments, - self.strip_comments, current_dir + self.strip_comments, current_dir, ) else: extracted = extract_from_dir( @@ -612,7 +612,7 @@ def finalize_options(self): def run(self): self.log.info( - 'creating catalog %s based on %s', self.output_file, self.input_file + 'creating catalog %s based on %s', self.output_file, self.input_file, ) with open(self.input_file, 'rb') as infile: @@ -701,7 +701,7 @@ def finalize_options(self): if not self.locale: raise OptionError( 'you must specify the locale for ' - 'the init-missing option to work' + 'the init-missing option to work', ) try: @@ -755,7 +755,7 @@ def run(self): check_status[filename] = False continue self.log.info( - 'creating catalog %s based on %s', filename, self.input_file + 'creating catalog %s based on %s', filename, self.input_file, ) with open(self.input_file, 'rb') as infile: @@ -841,7 +841,7 @@ class CommandLineInterface: 'compile': 'compile message catalogs to MO files', 'extract': 'extract messages from source files and generate a POT file', 'init': 'create new message catalogs from a POT file', - 'update': 'update existing message catalogs from a POT file' + 'update': 'update existing message catalogs from a POT file', } command_classes = { @@ -935,7 +935,7 @@ def _configure_command(self, cmdname, argv): parser = optparse.OptionParser( usage=self.usage % (cmdname, ''), - description=self.commands[cmdname] + description=self.commands[cmdname], ) as_args = getattr(cmdclass, "as_args", ()) for long, short, help in cmdclass.user_options: diff --git a/babel/messages/jslexer.py b/babel/messages/jslexer.py index cf287e450..6456bd038 100644 --- a/babel/messages/jslexer.py +++ b/babel/messages/jslexer.py @@ -18,7 +18,7 @@ '+', '-', '*', '%', '!=', '==', '<', '>', '<=', '>=', '=', '+=', '-=', '*=', '%=', '<<', '>>', '>>>', '<<=', '>>=', '>>>=', '&', '&=', '|', '|=', '&&', '||', '^', '^=', '(', ')', - '[', ']', '{', '}', '!', '--', '++', '~', ',', ';', '.', ':' + '[', ']', '{', '}', '!', '--', '++', '~', ',', ';', '.', ':', ], key=len, reverse=True) escapes: dict[str, str] = {'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t'} @@ -58,7 +58,7 @@ class Token(NamedTuple): ('string', re.compile(r'''( '(?:[^'\\]*(?:\\.[^'\\]*)*)' | "(?:[^"\\]*(?:\\.[^"\\]*)*)" - )''', re.VERBOSE | re.DOTALL)) + )''', re.VERBOSE | re.DOTALL)), ] diff --git a/babel/messages/mofile.py b/babel/messages/mofile.py index 4ec58cac7..ca02e6837 100644 --- a/babel/messages/mofile.py +++ b/babel/messages/mofile.py @@ -208,5 +208,5 @@ def write_mo(fileobj: SupportsWrite[bytes], catalog: Catalog, use_fuzzy: bool = len(messages), # number of entries 7 * 4, # start of key index 7 * 4 + len(messages) * 8, # start of value index - 0, 0 # size and offset of hash table + 0, 0, # size and offset of hash table ) + array.array.tobytes(array.array("i", offsets)) + ids + strs) diff --git a/babel/messages/plurals.py b/babel/messages/plurals.py index 5341b8356..fa3f03ed8 100644 --- a/babel/messages/plurals.py +++ b/babel/messages/plurals.py @@ -65,7 +65,7 @@ 6, '(n==1 ? 0 : n%10==1 && n%100!=11 && n%100!=71 && n%100!=91 ? 1 : n%10==2 && n%100!=12 && n%100!=72 && ' 'n%100!=92 ? 2 : (n%10==3 || n%10==4 || n%10==9) && n%100!=13 && n%100!=14 && n%100!=19 && n%100!=73 && ' - 'n%100!=74 && n%100!=79 && n%100!=93 && n%100!=94 && n%100!=99 ? 3 : n%1000000==0 ? 4 : 5)' + 'n%100!=74 && n%100!=79 && n%100!=93 && n%100!=94 && n%100!=99 ? 3 : n%1000000==0 ? 4 : 5)', ), # Bosnian 'bs': (3, '(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)'), diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py index 3c8a523e0..b64a5085e 100644 --- a/babel/messages/pofile.py +++ b/babel/messages/pofile.py @@ -617,7 +617,7 @@ def _write_message(message, prefix=''): ) if len(message.previous_id) > 1: _write_comment('msgid_plural %s' % _normalize( - message.previous_id[1] + message.previous_id[1], ), prefix='|') _write_message(message) @@ -626,7 +626,7 @@ def _write_message(message, prefix=''): if not ignore_obsolete: for message in _sort_messages( catalog.obsolete.values(), - sort_by=sort_by + sort_by=sort_by, ): for comment in message.user_comments: _write_comment(comment) diff --git a/babel/messages/setuptools_frontend.py b/babel/messages/setuptools_frontend.py index 2f23fc182..67b9f24e1 100644 --- a/babel/messages/setuptools_frontend.py +++ b/babel/messages/setuptools_frontend.py @@ -28,7 +28,7 @@ def check_message_extractors(dist, name, value): assert name == "message_extractors" if not isinstance(value, dict): raise SetupError( - 'the value of the "message_extractors" parameter must be a dictionary' + 'the value of the "message_extractors" parameter must be a dictionary', ) diff --git a/babel/numbers.py b/babel/numbers.py index e0df40cce..c6fcb9504 100644 --- a/babel/numbers.py +++ b/babel/numbers.py @@ -721,7 +721,7 @@ def format_compact_currency( *, format_type: Literal["short"] = "short", locale: Locale | str | None = LC_NUMERIC, - fraction_digits: int = 0 + fraction_digits: int = 0, ) -> str: """Format a number as a currency value in compact form. @@ -1216,7 +1216,7 @@ def apply( self._quantize_value(value, locale, frac_prec, group_separator), get_exponential_symbol(locale), exp_sign, # type: ignore # exp_sign is always defined here - self._format_int(str(exp), self.exp_prec[0], self.exp_prec[1], locale) # type: ignore # exp is always defined here + self._format_int(str(exp), self.exp_prec[0], self.exp_prec[1], locale), # type: ignore # exp is always defined here ]) # Is it a significant digits pattern? diff --git a/babel/plural.py b/babel/plural.py index 9d368481c..01df16c6d 100644 --- a/babel/plural.py +++ b/babel/plural.py @@ -342,7 +342,7 @@ class RuleError(Exception): ('word', re.compile(fr'\b(and|or|is|(?:with)?in|not|mod|[{"".join(_VARS)}])\b')), ('value', re.compile(r'\d+')), ('symbol', re.compile(r'%|,|!=|=')), - ('ellipsis', re.compile(r'\.{2,3}|\u2026', re.UNICODE)) # U+2026: ELLIPSIS + ('ellipsis', re.compile(r'\.{2,3}|\u2026', re.UNICODE)), # U+2026: ELLIPSIS ] diff --git a/babel/support.py b/babel/support.py index 43b406349..8d03934a3 100644 --- a/babel/support.py +++ b/babel/support.py @@ -344,7 +344,7 @@ def __copy__(self) -> LazyProxy: self._func, enable_cache=self._is_cache_enabled, *self._args, # noqa: B026 - **self._kwargs + **self._kwargs, ) def __deepcopy__(self, memo: Any) -> LazyProxy: @@ -353,7 +353,7 @@ def __deepcopy__(self, memo: Any) -> LazyProxy: deepcopy(self._func, memo), enable_cache=deepcopy(self._is_cache_enabled, memo), *deepcopy(self._args, memo), # noqa: B026 - **deepcopy(self._kwargs, memo) + **deepcopy(self._kwargs, memo), ) diff --git a/babel/units.py b/babel/units.py index 7b0e144de..465d2263d 100644 --- a/babel/units.py +++ b/babel/units.py @@ -271,7 +271,7 @@ def format_compound_unit( formatted_numerator = numerator_value elif numerator_unit: # Numerator has unit formatted_numerator = format_unit( - numerator_value, numerator_unit, length=length, format=format, locale=locale + numerator_value, numerator_unit, length=length, format=format, locale=locale, ) else: # Unitless numerator formatted_numerator = format_decimal(numerator_value, format=format, locale=locale) diff --git a/babel/util.py b/babel/util.py index 17b08d1ec..093197f9f 100644 --- a/babel/util.py +++ b/babel/util.py @@ -202,7 +202,7 @@ def pathmatch(pattern: str, filename: str) -> bool: class TextWrapper(textwrap.TextWrapper): wordsep_re = re.compile( r'(\s+|' # any whitespace - r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))' # em-dash + r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))', # em-dash ) diff --git a/docs/conf.py b/docs/conf.py index df7382766..5e4ade202 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -138,7 +138,7 @@ 'index': ['sidebar-about.html', 'localtoc.html', 'sidebar-links.html', 'searchbox.html'], '**': ['sidebar-logo.html', 'localtoc.html', 'relations.html', - 'searchbox.html'] + 'searchbox.html'], } # Additional templates that should be rendered to pages, maps page names to diff --git a/pyproject.toml b/pyproject.toml index dbd137cff..c90b6e45e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,6 +3,7 @@ target-version = "py37" select = [ "B", "C", + "COM", "E", "F", "I", diff --git a/scripts/import_cldr.py b/scripts/import_cldr.py index 96b6c9438..15d533980 100755 --- a/scripts/import_cldr.py +++ b/scripts/import_cldr.py @@ -23,7 +23,7 @@ # Make sure we're using Babel source, and not some previously installed version CHECKOUT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), - '..' + '..', )) BABEL_PACKAGE_ROOT = os.path.join(CHECKOUT_ROOT, "babel") sys.path.insert(0, CHECKOUT_ROOT) @@ -55,7 +55,7 @@ def _text(elem): 'eraAbbr': 'abbreviated', 'eraNames': 'wide', 'eraNarrow': 'narrow', - 'timeFormats': 'time_formats' + 'timeFormats': 'time_formats', } log = logging.getLogger("import_cldr") @@ -164,11 +164,11 @@ def main(): parser = OptionParser(usage='%prog path/to/cldr') parser.add_option( '-f', '--force', dest='force', action='store_true', default=False, - help='force import even if destination file seems up to date' + help='force import even if destination file seems up to date', ) parser.add_option( '-j', '--json', dest='dump_json', action='store_true', default=False, - help='also export debugging JSON dumps of locale data' + help='also export debugging JSON dumps of locale data', ) parser.add_option( '-q', '--quiet', dest='quiet', action='store_true', default=bool(os.environ.get('BABEL_CLDR_QUIET')), @@ -187,7 +187,7 @@ def main(): srcdir=args[0], destdir=BABEL_PACKAGE_ROOT, force=bool(options.force), - dump_json=bool(options.dump_json) + dump_json=bool(options.dump_json), ) @@ -399,7 +399,7 @@ def _process_local_datas(sup, srcdir, destdir, force=False, dump_json=False): locale_id = '_'.join(filter(None, [ language, - territory != '001' and territory or None + territory != '001' and territory or None, ])) data['locale_id'] = locale_id @@ -448,7 +448,7 @@ def _process_local_datas(sup, srcdir, destdir, force=False, dump_json=False): if unsupported_number_systems_string: log.warning( f"{locale_id}: unsupported number systems were ignored: " - f"{unsupported_number_systems_string}" + f"{unsupported_number_systems_string}", ) write_datafile(data_filename, data, dump_json=dump_json) @@ -616,7 +616,7 @@ def parse_calendar_months(data, calendar): elif elem.tag == 'alias': ctxts[width_type] = Alias( _translate_alias(['months', ctxt_type, width_type], - elem.attrib['path']) + elem.attrib['path']), ) @@ -634,7 +634,7 @@ def parse_calendar_days(data, calendar): elif elem.tag == 'alias': ctxts[width_type] = Alias( _translate_alias(['days', ctxt_type, width_type], - elem.attrib['path']) + elem.attrib['path']), ) @@ -667,7 +667,7 @@ def parse_calendar_eras(data, calendar): elif elem.tag == 'alias': eras[width_type] = Alias( _translate_alias(['eras', width_type], - elem.attrib['path']) + elem.attrib['path']), ) @@ -695,13 +695,13 @@ def parse_calendar_date_formats(data, calendar): continue try: date_formats[type] = dates.parse_pattern( - str(elem.findtext('dateFormat/pattern')) + str(elem.findtext('dateFormat/pattern')), ) except ValueError as e: log.error(e) elif elem.tag == 'alias': date_formats = Alias(_translate_alias( - ['date_formats'], elem.attrib['path']) + ['date_formats'], elem.attrib['path']), ) @@ -715,13 +715,13 @@ def parse_calendar_time_formats(data, calendar): continue try: time_formats[type] = dates.parse_pattern( - str(elem.findtext('timeFormat/pattern')) + str(elem.findtext('timeFormat/pattern')), ) except ValueError as e: log.error(e) elif elem.tag == 'alias': time_formats = Alias(_translate_alias( - ['time_formats'], elem.attrib['path']) + ['time_formats'], elem.attrib['path']), ) @@ -740,7 +740,7 @@ def parse_calendar_datetime_skeletons(data, calendar): log.error(e) elif elem.tag == 'alias': datetime_formats = Alias(_translate_alias( - ['datetime_formats'], elem.attrib['path']) + ['datetime_formats'], elem.attrib['path']), ) elif elem.tag == 'availableFormats': for datetime_skeleton in elem.findall('dateFormatItem'): @@ -933,7 +933,7 @@ def parse_currency_formats(data, tree): if child.tag == 'alias': currency_formats[type] = Alias( _translate_alias(['currency_formats', elem.attrib['type']], - child.attrib['path']) + child.attrib['path']), ) elif child.tag == 'pattern': pattern_type = child.attrib.get('type') diff --git a/setup.py b/setup.py index 5233af1c8..4da20aabf 100755 --- a/setup.py +++ b/setup.py @@ -102,5 +102,5 @@ def run(self): ignore = babel.messages.extract:extract_nothing python = babel.messages.extract:extract_python javascript = babel.messages.extract:extract_javascript - """ + """, ) diff --git a/tests/messages/test_extract.py b/tests/messages/test_extract.py index 63f4d1052..086702ed7 100644 --- a/tests/messages/test_extract.py +++ b/tests/messages/test_extract.py @@ -119,7 +119,7 @@ class Meta: assert messages == [ (3, '_', 'Page arg 1', []), (3, '_', 'Page arg 2', []), - (8, '_', 'log entry', []) + (8, '_', 'log entry', []), ] def test_multiline(self): diff --git a/tests/messages/test_frontend.py b/tests/messages/test_frontend.py index a5f436305..53be75611 100644 --- a/tests/messages/test_frontend.py +++ b/tests/messages/test_frontend.py @@ -277,7 +277,7 @@ def test_extraction_with_mapping_dict(self): 'project': [ ('**/ignored/**.*', 'ignore', None), ('**.py', 'python', None), - ] + ], } self.cmd.copyright_holder = 'FooBar, Inc.' self.cmd.msgid_bugs_address = 'bugs.address@email.tld' @@ -332,7 +332,7 @@ def test_extraction_add_location_file(self): 'project': [ ('**/ignored/**.*', 'ignore', None), ('**.py', 'python', None), - ] + ], } self.cmd.output_file = 'project/i18n/temp.pot' self.cmd.add_location = 'file' @@ -1168,7 +1168,7 @@ def test_update(self): self.cli.run(sys.argv + ['init', '-l', 'fi', '-o', po_file, - '-i', tmpl_file + '-i', tmpl_file, ]) with open(po_file) as infp: catalog = read_po(infp) @@ -1202,7 +1202,7 @@ def test_update_pot_creation_date(self): self.cli.run(sys.argv + ['init', '-l', 'fi', '-o', po_file, - '-i', tmpl_file + '-i', tmpl_file, ]) with open(po_file) as infp: catalog = read_po(infp) @@ -1256,7 +1256,7 @@ def test_check(self): self.cli.run(sys.argv + ['init', '-l', 'fi_FI', '-o', po_file, - '-i', tmpl_file + '-i', tmpl_file, ]) # Update the catalog file @@ -1314,7 +1314,7 @@ def test_check_pot_creation_date(self): self.cli.run(sys.argv + ['init', '-l', 'fi_FI', '-o', po_file, - '-i', tmpl_file + '-i', tmpl_file, ]) # Update the catalog file @@ -1441,7 +1441,7 @@ def test_parse_keywords_with_t(): None: (1,), 2: (2,), 3: ((2, 'c'), 3), - } + }, } @@ -1504,7 +1504,7 @@ def test_extract_keyword_args_384(split, arg_name): # (Both of those invocation styles should be equivalent, so there is no parametrization from here on out) cmdinst = configure_cli_command( - f"extract -F babel-django.cfg --add-comments Translators: -o django232.pot {kwarg_text} ." + f"extract -F babel-django.cfg --add-comments Translators: -o django232.pot {kwarg_text} .", ) assert isinstance(cmdinst, ExtractMessages) assert set(cmdinst.keywords.keys()) == {'_', 'dgettext', 'dngettext', diff --git a/tests/messages/test_js_extract.py b/tests/messages/test_js_extract.py index 82f5379ea..fc643851e 100644 --- a/tests/messages/test_js_extract.py +++ b/tests/messages/test_js_extract.py @@ -39,7 +39,7 @@ def test_various_calls(): assert messages == [ (5, ('bunny', 'bunnies'), [], None), (8, 'Rabbit', [], None), - (10, ('Page', 'Pages'), [], None) + (10, ('Page', 'Pages'), [], None), ] @@ -130,7 +130,7 @@ def test_jsx_extraction(jsx_enabled): def test_dotted_keyword_extract(): buf = BytesIO(b"msg1 = com.corporate.i18n.formatMessage('Insert coin to continue')") messages = list( - extract.extract('javascript', buf, {"com.corporate.i18n.formatMessage": None}, [], {}) + extract.extract('javascript', buf, {"com.corporate.i18n.formatMessage": None}, [], {}), ) assert messages == [(1, 'Insert coin to continue', [], None)] @@ -139,7 +139,7 @@ def test_dotted_keyword_extract(): def test_template_string_standard_usage(): buf = BytesIO(b"msg1 = gettext(`Very template, wow`)") messages = list( - extract.extract('javascript', buf, {"gettext": None}, [], {}) + extract.extract('javascript', buf, {"gettext": None}, [], {}), ) assert messages == [(1, 'Very template, wow', [], None)] @@ -148,7 +148,7 @@ def test_template_string_standard_usage(): def test_template_string_tag_usage(): buf = BytesIO(b"function() { if(foo) msg1 = i18n`Tag template, wow`; }") messages = list( - extract.extract('javascript', buf, {"i18n": None}, [], {}) + extract.extract('javascript', buf, {"i18n": None}, [], {}), ) assert messages == [(1, 'Tag template, wow', [], None)] @@ -157,7 +157,7 @@ def test_template_string_tag_usage(): def test_inside_template_string(): buf = BytesIO(b"const msg = `${gettext('Hello')} ${user.name}`") messages = list( - extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}) + extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}), ) assert messages == [(1, 'Hello', [], None)] @@ -178,7 +178,7 @@ def test_inside_template_string_with_linebreaks(): }` """) messages = list( - extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}) + extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}), ) assert messages == [(1, 'Username', [], None), (3, 'Hello', [], None), (5, 'Are you having a nice day?', [], None), (8, 'Howdy', [], None), (10, 'Are you doing ok?', [], None)] @@ -187,7 +187,7 @@ def test_inside_template_string_with_linebreaks(): def test_inside_nested_template_string(): buf = BytesIO(b"const msg = `${gettext('Greetings!')} ${ evening ? `${user.name}: ${gettext('This is a lovely evening.')}` : `${gettext('The day is really nice!')} ${user.name}`}`") messages = list( - extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}) + extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True}), ) assert messages == [(1, 'Greetings!', [], None), (1, 'This is a lovely evening.', [], None), (1, 'The day is really nice!', [], None)] diff --git a/tests/messages/test_jslexer.py b/tests/messages/test_jslexer.py index 3889f0b3a..00afc78ae 100644 --- a/tests/messages/test_jslexer.py +++ b/tests/messages/test_jslexer.py @@ -17,7 +17,7 @@ def test_dotted_name(): ('name', 'foo.bar', 1), ('operator', '(', 1), ('name', 'quux', 1), - ('operator', ')', 1) + ('operator', ')', 1), ] @@ -30,7 +30,7 @@ def test_dotted_name_end(): def test_template_string(): assert list(jslexer.tokenize("gettext `foo\"bar\"p`", template_string=True)) == [ ('name', 'gettext', 1), - ('template_string', '`foo"bar"p`', 1) + ('template_string', '`foo"bar"p`', 1), ] @@ -121,5 +121,5 @@ def test_jsx(): ('operator', '}', 7), ('jsx_tag', '/>', 7), ('jsx_tag', '', 8) + ('operator', '>', 8), ] diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index acd8c6e34..043f9c8bd 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -580,10 +580,10 @@ def test_wrap_long_lines_in_header(self): def test_wrap_locations_with_hyphens(self): catalog = Catalog() catalog.add('foo', locations=[ - ('doupy/templates/base/navmenu.inc.html.py', 60) + ('doupy/templates/base/navmenu.inc.html.py', 60), ]) catalog.add('foo', locations=[ - ('doupy/templates/job-offers/helpers.html', 22) + ('doupy/templates/job-offers/helpers.html', 22), ]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) diff --git a/tests/test_dates.py b/tests/test_dates.py index f4f577397..d3f2ad9e7 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -569,7 +569,7 @@ def test_format_datetime(timezone_getter): full = dates.format_datetime( dt, 'full', tzinfo=timezone_getter('Europe/Paris'), - locale='fr_FR' + locale='fr_FR', ) assert full == ( 'dimanche 1 avril 2007, 17:30:00 heure ' @@ -578,7 +578,7 @@ def test_format_datetime(timezone_getter): custom = dates.format_datetime( dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz", tzinfo=timezone_getter('US/Eastern'), - locale='en' + locale='en', ) assert custom == '2007.04.01 AD at 11:30:00 EDT' diff --git a/tests/test_localedata.py b/tests/test_localedata.py index 1cc3a63b3..d4eb4e597 100644 --- a/tests/test_localedata.py +++ b/tests/test_localedata.py @@ -46,11 +46,11 @@ def test_merge_with_alias_and_resolve(self): alias = localedata.Alias('x') d1 = { 'x': {'a': 1, 'b': 2, 'c': 3}, - 'y': alias + 'y': alias, } d2 = { 'x': {'a': 1, 'b': 12, 'd': 14}, - 'y': {'b': 22, 'e': 25} + 'y': {'b': 22, 'e': 25}, } localedata.merge(d1, d2) assert d1 == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, 'y': (alias, {'b': 22, 'e': 25})} diff --git a/tests/test_numbers.py b/tests/test_numbers.py index 3674453f6..036780412 100644 --- a/tests/test_numbers.py +++ b/tests/test_numbers.py @@ -303,7 +303,7 @@ def test_get_territory_currencies(): 'currency': 'USD', 'from': date(1792, 1, 1), 'to': None, - 'tender': True + 'tender': True, }] assert numbers.get_territory_currencies('LS', date(2013, 1, 1)) == ['ZAR', 'LSL'] diff --git a/tests/test_plural.py b/tests/test_plural.py index 6fbf3af7e..2fa56cf4e 100644 --- a/tests/test_plural.py +++ b/tests/test_plural.py @@ -142,13 +142,43 @@ def test_locales_with_no_plural_rules_have_default(): WELL_FORMED_TOKEN_TESTS = ( - ('', []), - ('n = 1', [('value', '1'), ('symbol', '='), ('word', 'n'), ]), - ('n = 1 @integer 1', [('value', '1'), ('symbol', '='), ('word', 'n'), ]), - ('n is 1', [('value', '1'), ('word', 'is'), ('word', 'n'), ]), - ('n % 100 = 3..10', [('value', '10'), ('ellipsis', '..'), ('value', '3'), - ('symbol', '='), ('value', '100'), ('symbol', '%'), - ('word', 'n'), ]), + ("", []), + ( + "n = 1", + [ + ("value", "1"), + ("symbol", "="), + ("word", "n"), + ], + ), + ( + "n = 1 @integer 1", + [ + ("value", "1"), + ("symbol", "="), + ("word", "n"), + ], + ), + ( + "n is 1", + [ + ("value", "1"), + ("word", "is"), + ("word", "n"), + ], + ), + ( + "n % 100 = 3..10", + [ + ("value", "10"), + ("ellipsis", ".."), + ("value", "3"), + ("symbol", "="), + ("value", "100"), + ("symbol", "%"), + ("word", "n"), + ], + ), ) @@ -236,7 +266,7 @@ def test_or_and(self): ('relation', ('in', ('mod', (self.n, plural.value_node(100))), - (make_range_list((1, 19))))))) + (make_range_list((1, 19))))))), ))