Skip to content

Commit 39e5ba6

Browse files
committed
style: Apply pyupgrade
1 parent 46b3486 commit 39e5ba6

File tree

13 files changed

+106
-122
lines changed

13 files changed

+106
-122
lines changed
+2-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
from typing import Any, Callable, Dict
1+
from typing import Any, Callable
22

33
from .types import FluentType, fluent_date, fluent_number
44

55
NUMBER = fluent_number
66
DATETIME = fluent_date
77

88

9-
BUILTINS: Dict[str, Callable[[Any], FluentType]] = {
9+
BUILTINS: dict[str, Callable[[Any], FluentType]] = {
1010
"NUMBER": NUMBER,
1111
"DATETIME": DATETIME,
1212
}

fluent.runtime/fluent/runtime/bundle.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Union, cast
1+
from typing import TYPE_CHECKING, Any, Callable, Union, cast
22

33
import babel
44
import babel.numbers
@@ -34,16 +34,16 @@ class FluentBundle:
3434

3535
def __init__(
3636
self,
37-
locales: List[str],
38-
functions: Union[Dict[str, Callable[[Any], "FluentType"]], None] = None,
37+
locales: list[str],
38+
functions: Union[dict[str, Callable[[Any], "FluentType"]], None] = None,
3939
use_isolating: bool = True,
4040
):
4141
self.locales = locales
4242
self._functions = {**BUILTINS, **(functions or {})}
4343
self.use_isolating = use_isolating
44-
self._messages: Dict[str, Union[FTL.Message, FTL.Term]] = {}
45-
self._terms: Dict[str, Union[FTL.Message, FTL.Term]] = {}
46-
self._compiled: Dict[str, Message] = {}
44+
self._messages: dict[str, Union[FTL.Message, FTL.Term]] = {}
45+
self._terms: dict[str, Union[FTL.Message, FTL.Term]] = {}
46+
self._compiled: dict[str, Message] = {}
4747
# The compiler is not typed, and this cast is only valid for the public API
4848
self._compiler = cast(
4949
Callable[[Union[FTL.Message, FTL.Term]], Message], Compiler()
@@ -90,8 +90,8 @@ def _lookup(self, entry_id: str, term: bool = False) -> Message:
9090
return self._compiled[compiled_id]
9191

9292
def format_pattern(
93-
self, pattern: Pattern, args: Union[Dict[str, Any], None] = None
94-
) -> Tuple[Union[str, "FluentNone"], List[Exception]]:
93+
self, pattern: Pattern, args: Union[dict[str, Any], None] = None
94+
) -> tuple[Union[str, "FluentNone"], list[Exception]]:
9595
if args is not None:
9696
fluent_args = {
9797
argname: native_to_fluent(argvalue)
@@ -100,7 +100,7 @@ def format_pattern(
100100
else:
101101
fluent_args = {}
102102

103-
errors: List[Exception] = []
103+
errors: list[Exception] = []
104104
env = ResolverEnvironment(
105105
context=self, current=CurrentEnvironment(args=fluent_args), errors=errors
106106
)

fluent.runtime/fluent/runtime/fallback.py

+15-24
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,7 @@
11
import codecs
22
import os
3-
from typing import (
4-
TYPE_CHECKING,
5-
Any,
6-
Callable,
7-
Dict,
8-
Generator,
9-
List,
10-
Type,
11-
Union,
12-
cast,
13-
)
3+
from collections.abc import Generator
4+
from typing import TYPE_CHECKING, Any, Callable, Union, cast
145

156
from fluent.syntax import FluentParser
167

@@ -32,24 +23,24 @@ class FluentLocalization:
3223

3324
def __init__(
3425
self,
35-
locales: List[str],
36-
resource_ids: List[str],
26+
locales: list[str],
27+
resource_ids: list[str],
3728
resource_loader: "AbstractResourceLoader",
3829
use_isolating: bool = False,
39-
bundle_class: Type[FluentBundle] = FluentBundle,
40-
functions: Union[Dict[str, Callable[[Any], "FluentType"]], None] = None,
30+
bundle_class: type[FluentBundle] = FluentBundle,
31+
functions: Union[dict[str, Callable[[Any], "FluentType"]], None] = None,
4132
):
4233
self.locales = locales
4334
self.resource_ids = resource_ids
4435
self.resource_loader = resource_loader
4536
self.use_isolating = use_isolating
4637
self.bundle_class = bundle_class
4738
self.functions = functions
48-
self._bundle_cache: List[FluentBundle] = []
39+
self._bundle_cache: list[FluentBundle] = []
4940
self._bundle_it = self._iterate_bundles()
5041

5142
def format_value(
52-
self, msg_id: str, args: Union[Dict[str, Any], None] = None
43+
self, msg_id: str, args: Union[dict[str, Any], None] = None
5344
) -> str:
5445
for bundle in self._bundles():
5546
if not bundle.has_message(msg_id):
@@ -63,7 +54,7 @@ def format_value(
6354
) # Never FluentNone when format_pattern called externally
6455
return msg_id
6556

66-
def _create_bundle(self, locales: List[str]) -> FluentBundle:
57+
def _create_bundle(self, locales: list[str]) -> FluentBundle:
6758
return self.bundle_class(
6859
locales, functions=self.functions, use_isolating=self.use_isolating
6960
)
@@ -95,8 +86,8 @@ class AbstractResourceLoader:
9586
"""
9687

9788
def resources(
98-
self, locale: str, resource_ids: List[str]
99-
) -> Generator[List["Resource"], None, None]:
89+
self, locale: str, resource_ids: list[str]
90+
) -> Generator[list["Resource"], None, None]:
10091
"""
10192
Yield lists of FluentResource objects, corresponding to
10293
each of the resource_ids.
@@ -118,18 +109,18 @@ class FluentResourceLoader(AbstractResourceLoader):
118109
different roots.
119110
"""
120111

121-
def __init__(self, roots: Union[str, List[str]]):
112+
def __init__(self, roots: Union[str, list[str]]):
122113
"""
123114
Create a resource loader. The roots may be a string for a single
124115
location on disk, or a list of strings.
125116
"""
126117
self.roots = [roots] if isinstance(roots, str) else roots
127118

128119
def resources(
129-
self, locale: str, resource_ids: List[str]
130-
) -> Generator[List["Resource"], None, None]:
120+
self, locale: str, resource_ids: list[str]
121+
) -> Generator[list["Resource"], None, None]:
131122
for root in self.roots:
132-
resources: List[Any] = []
123+
resources: list[Any] = []
133124
for resource_id in resource_ids:
134125
path = self.localize_path(os.path.join(root, resource_id), locale)
135126
if not os.path.isfile(path):

fluent.runtime/fluent/runtime/prepare.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, List
1+
from typing import Any
22

33
from fluent.syntax import ast as FTL
44

@@ -17,7 +17,7 @@ def compile(self, node: Any) -> Any:
1717
nodename: str = type(node).__name__
1818
if not hasattr(resolver, nodename):
1919
return node
20-
kwargs: Dict[str, Any] = vars(node).copy()
20+
kwargs: dict[str, Any] = vars(node).copy()
2121
for propname, propvalue in kwargs.items():
2222
kwargs[propname] = self(propvalue)
2323
handler = getattr(self, "compile_" + nodename, self.compile_generic)
@@ -31,7 +31,7 @@ def compile_Placeable(self, _: Any, expression: Any, **kwargs: Any) -> Any:
3131
return expression
3232
return resolver.Placeable(expression=expression, **kwargs)
3333

34-
def compile_Pattern(self, _: Any, elements: List[Any], **kwargs: Any) -> Any:
34+
def compile_Pattern(self, _: Any, elements: list[Any], **kwargs: Any) -> Any:
3535
if len(elements) == 1 and isinstance(elements[0], resolver.Placeable):
3636
# Don't isolate isolated placeables
3737
return resolver.NeverIsolatingPlaceable(elements[0].expression)

fluent.runtime/fluent/runtime/resolver.py

+16-15
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import contextlib
2-
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Set, Union, cast
2+
from collections.abc import Generator
3+
from typing import TYPE_CHECKING, Any, Union, cast
34

45
import attr
56
from fluent.syntax import ast as FTL
@@ -42,7 +43,7 @@ class CurrentEnvironment:
4243
# For Messages, VariableReference nodes are interpreted as external args,
4344
# but for Terms they are the values explicitly passed using CallExpression
4445
# syntax. So we have to be able to change 'args' for this purpose.
45-
args: Dict[str, Any] = attr.ib(factory=dict)
46+
args: dict[str, Any] = attr.ib(factory=dict)
4647
# This controls whether we need to report an error if a VariableReference
4748
# refers to an arg that is not present in the args dict.
4849
error_for_missing_arg: bool = attr.ib(default=True)
@@ -51,9 +52,9 @@ class CurrentEnvironment:
5152
@attr.s
5253
class ResolverEnvironment:
5354
context: "FluentBundle" = attr.ib()
54-
errors: List[Exception] = attr.ib()
55+
errors: list[Exception] = attr.ib()
5556
part_count: int = attr.ib(default=0, init=False)
56-
active_patterns: Set[FTL.Pattern] = attr.ib(factory=set, init=False)
57+
active_patterns: set[FTL.Pattern] = attr.ib(factory=set, init=False)
5758
current: CurrentEnvironment = attr.ib(factory=CurrentEnvironment)
5859

5960
@contextlib.contextmanager
@@ -72,7 +73,7 @@ def modified(
7273
self.current = old_current
7374

7475
def modified_for_term_reference(
75-
self, args: Union[Dict[str, Any], None] = None
76+
self, args: Union[dict[str, Any], None] = None
7677
) -> Any:
7778
return self.modified(
7879
args=args if args is not None else {}, error_for_missing_arg=False
@@ -100,13 +101,13 @@ class Literal(BaseResolver):
100101
class Message(FTL.Entry, BaseResolver):
101102
id: "Identifier"
102103
value: Union["Pattern", None]
103-
attributes: Dict[str, "Pattern"]
104+
attributes: dict[str, "Pattern"]
104105

105106
def __init__(
106107
self,
107108
id: "Identifier",
108109
value: Union["Pattern", None] = None,
109-
attributes: Union[List["Attribute"], None] = None,
110+
attributes: Union[list["Attribute"], None] = None,
110111
comment: Any = None,
111112
**kwargs: Any,
112113
):
@@ -121,13 +122,13 @@ def __init__(
121122
class Term(FTL.Entry, BaseResolver):
122123
id: "Identifier"
123124
value: "Pattern"
124-
attributes: Dict[str, "Pattern"]
125+
attributes: dict[str, "Pattern"]
125126

126127
def __init__(
127128
self,
128129
id: "Identifier",
129130
value: "Pattern",
130-
attributes: Union[List["Attribute"], None] = None,
131+
attributes: Union[list["Attribute"], None] = None,
131132
comment: Any = None,
132133
**kwargs: Any,
133134
):
@@ -143,7 +144,7 @@ class Pattern(FTL.Pattern, BaseResolver):
143144
# Prevent messages with too many sub parts, for CPI DOS protection
144145
MAX_PARTS = 1000
145146

146-
elements: List[Union["TextElement", "Placeable"]] # type: ignore
147+
elements: list[Union["TextElement", "Placeable"]] # type: ignore
147148

148149
def __init__(self, *args: Any, **kwargs: Any):
149150
super().__init__(*args, **kwargs)
@@ -294,7 +295,7 @@ def __call__(self, env: ResolverEnvironment) -> Any:
294295
if isinstance(arg_val, (FluentType, str)):
295296
return arg_val
296297
env.errors.append(
297-
TypeError("Unsupported external type: {}, {}".format(name, type(arg_val)))
298+
TypeError(f"Unsupported external type: {name}, {type(arg_val)}")
298299
)
299300
return FluentNone(name)
300301

@@ -306,7 +307,7 @@ class Attribute(FTL.Attribute, BaseResolver):
306307

307308
class SelectExpression(FTL.SelectExpression, BaseResolver):
308309
selector: "InlineExpression"
309-
variants: List["Variant"] # type: ignore
310+
variants: list["Variant"] # type: ignore
310311

311312
def __call__(self, env: ResolverEnvironment) -> Union[str, FluentNone]:
312313
key = self.selector(env)
@@ -368,8 +369,8 @@ def __call__(self, env: ResolverEnvironment) -> str:
368369

369370

370371
class CallArguments(FTL.CallArguments, BaseResolver):
371-
positional: List[Union["InlineExpression", Placeable]] # type: ignore
372-
named: List["NamedArgument"] # type: ignore
372+
positional: list[Union["InlineExpression", Placeable]] # type: ignore
373+
named: list["NamedArgument"] # type: ignore
373374

374375

375376
class FunctionReference(FTL.FunctionReference, BaseResolver):
@@ -384,7 +385,7 @@ def __call__(self, env: ResolverEnvironment) -> Any:
384385
function = env.context._functions[function_name]
385386
except LookupError:
386387
env.errors.append(
387-
FluentReferenceError("Unknown function: {}".format(function_name))
388+
FluentReferenceError(f"Unknown function: {function_name}")
388389
)
389390
return FluentNone(function_name + "()")
390391

fluent.runtime/fluent/runtime/types.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import warnings
22
from datetime import date, datetime
33
from decimal import Decimal
4-
from typing import Any, Dict, Type, TypeVar, Union, cast
4+
from typing import Any, TypeVar, Union, cast
55

66
import attr
77
import pytz
@@ -106,7 +106,7 @@ def __new__(
106106
return self._init(value, kwargs)
107107

108108
def _init(
109-
self, value: Union[int, float, Decimal, "FluentNumber"], kwargs: Dict[str, Any]
109+
self, value: Union[int, float, Decimal, "FluentNumber"], kwargs: dict[str, Any]
110110
) -> "FluentNumber":
111111
self.options = merge_options(
112112
NumberFormatOptions,
@@ -211,7 +211,7 @@ def replacer(s: str) -> str:
211211

212212

213213
def merge_options(
214-
options_class: Type[Options], base: Union[Options, None], kwargs: Dict[str, Any]
214+
options_class: type[Options], base: Union[Options, None], kwargs: dict[str, Any]
215215
) -> Options:
216216
"""
217217
Given an 'options_class', an optional 'base' object to copy from,
@@ -346,7 +346,7 @@ class FluentDateType(FluentType):
346346
# So we leave those alone, and implement another `_init_options`
347347
# which is called from other constructors.
348348
def _init_options(
349-
self, dt_obj: Union[date, datetime], kwargs: Dict[str, Any]
349+
self, dt_obj: Union[date, datetime], kwargs: dict[str, Any]
350350
) -> None:
351351
if "timeStyle" in kwargs and not isinstance(self, datetime):
352352
raise TypeError(
@@ -437,6 +437,4 @@ def fluent_date(
437437
elif isinstance(dt, FluentNone):
438438
return dt
439439
else:
440-
raise TypeError(
441-
"Can't use fluent_date with object {} of type {}".format(dt, type(dt))
442-
)
440+
raise TypeError(f"Can't use fluent_date with object {dt} of type {type(dt)}")

fluent.runtime/tests/test_types.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,7 @@
55

66
import pytz
77
from babel import Locale
8-
from fluent.runtime.types import (
9-
FluentDateType,
10-
FluentNumber,
11-
fluent_date,
12-
fluent_number,
13-
)
8+
from fluent.runtime.types import FluentDateType, FluentNumber, fluent_date, fluent_number
149

1510

1611
class TestFluentNumber(unittest.TestCase):

fluent.runtime/tools/benchmarks/fluent_benchmark.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python
22
# This should be run using pytest
33

4-
from __future__ import unicode_literals
54

65
import sys
76

@@ -48,7 +47,7 @@ def fluent_template(bundle):
4847
)
4948

5049

51-
class TestBenchmark(object):
50+
class TestBenchmark:
5251
def test_template(self, fluent_bundle, benchmark):
5352
benchmark(lambda: fluent_template(fluent_bundle))
5453

0 commit comments

Comments
 (0)