Skip to content

Commit 3ac7198

Browse files
oprypincopybara-github
authored andcommitted
Modernize type annotations using Python 3.10+ features
This is supposed to be a no-op change, but minor differences in the underlying implementation *could* happen. PiperOrigin-RevId: 861602144
1 parent c5a6e0a commit 3ac7198

File tree

14 files changed

+412
-384
lines changed

14 files changed

+412
-384
lines changed

absl/app.pyi

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
1-
from typing import Any, Callable, Collection, Iterable, List, NoReturn, Optional, TypeVar, Union, overload
1+
from collections.abc import Callable
2+
from typing import Any, NoReturn, TypeVar, overload
23

34
from absl.flags import _flag
45

56
_MainArgs = TypeVar('_MainArgs')
67
_Exc = TypeVar('_Exc', bound=Exception)
78

8-
class ExceptionHandler():
9+
class ExceptionHandler:
910

1011
def wants(self, exc: _Exc) -> bool:
1112
...
1213

1314
def handle(self, exc: _Exc):
1415
...
1516

16-
EXCEPTION_HANDLERS: List[ExceptionHandler] = ...
17+
EXCEPTION_HANDLERS: list[ExceptionHandler] = ...
1718

1819
class HelpFlag(_flag.BooleanFlag):
1920
def __init__(self):
@@ -34,23 +35,23 @@ def define_help_flags() -> None:
3435
...
3536

3637
@overload
37-
def usage(shorthelp: Union[bool, int] = ...,
38-
writeto_stdout: Union[bool, int] = ...,
39-
detailed_error: Optional[Any] = ...,
38+
def usage(shorthelp: bool | int = ...,
39+
writeto_stdout: bool | int = ...,
40+
detailed_error: Any | None = ...,
4041
exitcode: None = ...) -> None:
4142
...
4243

4344
@overload
44-
def usage(shorthelp: Union[bool, int],
45-
writeto_stdout: Union[bool, int],
46-
detailed_error: Optional[Any],
45+
def usage(shorthelp: bool | int,
46+
writeto_stdout: bool | int,
47+
detailed_error: Any | None,
4748
exitcode: int) -> NoReturn:
4849
...
4950

5051
@overload
51-
def usage(shorthelp: Union[bool, int] = ...,
52-
writeto_stdout: Union[bool, int] = ...,
53-
detailed_error: Optional[Any] = ...,
52+
def usage(shorthelp: bool | int = ...,
53+
writeto_stdout: bool | int = ...,
54+
detailed_error: Any | None = ...,
5455
*,
5556
exitcode: int) -> NoReturn:
5657
...
@@ -64,7 +65,7 @@ class Error(Exception):
6465
class UsageError(Error):
6566
exitcode: int
6667

67-
def parse_flags_with_usage(args: List[str]) -> List[str]:
68+
def parse_flags_with_usage(args: list[str]) -> list[str]:
6869
...
6970

7071
def call_after_init(callback: Callable[[], Any]) -> None:
@@ -73,16 +74,16 @@ def call_after_init(callback: Callable[[], Any]) -> None:
7374
# Without the flag_parser argument, `main` should require a List[str].
7475
@overload
7576
def run(
76-
main: Callable[[List[str]], Any],
77-
argv: Optional[List[str]] = ...,
77+
main: Callable[[list[str]], Any],
78+
argv: list[str] | None = ...,
7879
) -> NoReturn:
7980
...
8081

8182
@overload
8283
def run(
8384
main: Callable[[_MainArgs], Any],
84-
argv: Optional[List[str]] = ...,
85+
argv: list[str] | None = ...,
8586
*,
86-
flags_parser: Callable[[List[str]], _MainArgs],
87+
flags_parser: Callable[[list[str]], _MainArgs],
8788
) -> NoReturn:
8889
...

absl/flags/_argument_parser.py

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@
1919
"""
2020

2121
import collections
22+
from collections.abc import Iterable, Sequence
2223
import csv
2324
import enum
2425
import io
2526
import string
26-
from typing import Any, Dict, Generic, Iterable, List, Optional, Sequence, Type, TypeVar, Union
27+
from typing import Any, Generic, TypeVar
2728
from xml.dom import minidom
2829

2930
from absl.flags import _helpers
@@ -36,7 +37,7 @@
3637
class _ArgumentParserCache(type):
3738
"""Metaclass used to cache and share argument parsers among flags."""
3839

39-
_instances: Dict[Any, Any] = {}
40+
_instances: dict[Any, Any] = {}
4041

4142
def __call__(cls, *args, **kwargs):
4243
"""Returns an instance of the argument parser cls.
@@ -91,7 +92,7 @@ class ArgumentParser(Generic[_T], metaclass=_ArgumentParserCache):
9192

9293
syntactic_help: str = ''
9394

94-
def parse(self, argument: str) -> Optional[_T]:
95+
def parse(self, argument: str) -> _T | None:
9596
"""Parses the string argument and returns the native value.
9697
9798
By default it returns its argument unmodified.
@@ -117,7 +118,7 @@ def flag_type(self) -> str:
117118

118119
def _custom_xml_dom_elements(
119120
self, doc: minidom.Document
120-
) -> List[minidom.Element]:
121+
) -> list[minidom.Element]:
121122
"""Returns a list of minidom.Element to add additional flag information.
122123
123124
Args:
@@ -141,15 +142,15 @@ class NumericParser(ArgumentParser[_N]):
141142
Parsed value may be bounded to a given upper and lower bound.
142143
"""
143144

144-
lower_bound: Optional[_N]
145-
upper_bound: Optional[_N]
145+
lower_bound: _N | None
146+
upper_bound: _N | None
146147

147148
def is_outside_bounds(self, val: _N) -> bool:
148149
"""Returns whether the value is outside the bounds or not."""
149150
return ((self.lower_bound is not None and val < self.lower_bound) or
150151
(self.upper_bound is not None and val > self.upper_bound))
151152

152-
def parse(self, argument: Union[str, _N]) -> _N:
153+
def parse(self, argument: str | _N) -> _N:
153154
"""See base class."""
154155
val = self.convert(argument)
155156
if self.is_outside_bounds(val):
@@ -158,7 +159,7 @@ def parse(self, argument: Union[str, _N]) -> _N:
158159

159160
def _custom_xml_dom_elements(
160161
self, doc: minidom.Document
161-
) -> List[minidom.Element]:
162+
) -> list[minidom.Element]:
162163
elements = []
163164
if self.lower_bound is not None:
164165
elements.append(_helpers.create_xml_dom_element(
@@ -168,7 +169,7 @@ def _custom_xml_dom_elements(
168169
doc, 'upper_bound', self.upper_bound))
169170
return elements
170171

171-
def convert(self, argument: Union[str, _N]) -> _N:
172+
def convert(self, argument: str | _N) -> _N:
172173
"""Returns the correct numeric value of argument.
173174
174175
Subclass must implement this method, and raise TypeError if argument is not
@@ -195,8 +196,8 @@ class FloatParser(NumericParser[float]):
195196

196197
def __init__(
197198
self,
198-
lower_bound: Optional[float] = None,
199-
upper_bound: Optional[float] = None,
199+
lower_bound: float | None = None,
200+
upper_bound: float | None = None,
200201
) -> None:
201202
super().__init__()
202203
self.lower_bound = lower_bound
@@ -214,7 +215,7 @@ def __init__(
214215
sh = '%s >= %s' % (self.number_name, lower_bound)
215216
self.syntactic_help = sh
216217

217-
def convert(self, argument: Union[int, float, str]) -> float:
218+
def convert(self, argument: int | float | str) -> float:
218219
"""Returns the float value of argument."""
219220
if (
220221
(isinstance(argument, int) and not isinstance(argument, bool))
@@ -242,7 +243,7 @@ class IntegerParser(NumericParser[int]):
242243
syntactic_help = ' '.join((number_article, number_name))
243244

244245
def __init__(
245-
self, lower_bound: Optional[int] = None, upper_bound: Optional[int] = None
246+
self, lower_bound: int | None = None, upper_bound: int | None = None
246247
) -> None:
247248
super().__init__()
248249
self.lower_bound = lower_bound
@@ -264,7 +265,7 @@ def __init__(
264265
sh = '%s >= %s' % (self.number_name, lower_bound)
265266
self.syntactic_help = sh
266267

267-
def convert(self, argument: Union[int, str]) -> int:
268+
def convert(self, argument: int | str) -> int:
268269
"""Returns the int value of argument."""
269270
if isinstance(argument, int) and not isinstance(argument, bool):
270271
return argument
@@ -288,7 +289,7 @@ def flag_type(self) -> str:
288289
class BooleanParser(ArgumentParser[bool]):
289290
"""Parser of boolean values."""
290291

291-
def parse(self, argument: Union[str, int]) -> bool:
292+
def parse(self, argument: str | int) -> bool:
292293
"""See base class."""
293294
if isinstance(argument, str):
294295
if argument.lower() in ('true', 't', '1'):
@@ -371,7 +372,7 @@ class EnumClassParser(ArgumentParser[_ET]):
371372
"""Parser of an Enum class member."""
372373

373374
def __init__(
374-
self, enum_class: Type[_ET], case_sensitive: bool = True
375+
self, enum_class: type[_ET], case_sensitive: bool = True
375376
) -> None:
376377
"""Initializes EnumParser.
377378
@@ -414,7 +415,7 @@ def member_names(self) -> Sequence[str]:
414415
"""The accepted enum names, in lowercase if not case sensitive."""
415416
return self._member_names
416417

417-
def parse(self, argument: Union[_ET, str]) -> _ET:
418+
def parse(self, argument: _ET | str) -> _ET:
418419
"""Determines validity of argument and returns the correct element of enum.
419420
420421
Args:
@@ -447,12 +448,12 @@ def flag_type(self) -> str:
447448
return 'enum class'
448449

449450

450-
class ListSerializer(Generic[_T], ArgumentSerializer[List[_T]]):
451+
class ListSerializer(Generic[_T], ArgumentSerializer[list[_T]]):
451452

452453
def __init__(self, list_sep: str) -> None:
453454
self.list_sep = list_sep
454455

455-
def serialize(self, value: List[_T]) -> str:
456+
def serialize(self, value: list[_T]) -> str:
456457
"""See base class."""
457458
return self.list_sep.join([str(x) for x in value])
458459

@@ -477,7 +478,7 @@ def __init__(self, list_sep: str, **kwargs) -> None:
477478
super().__init__(list_sep)
478479
self._element_serializer = EnumClassSerializer(**kwargs)
479480

480-
def serialize(self, value: Union[_ET, List[_ET]]) -> str:
481+
def serialize(self, value: _ET | list[_ET]) -> str:
481482
"""See base class."""
482483
if isinstance(value, list):
483484
return self.list_sep.join(
@@ -488,7 +489,7 @@ def serialize(self, value: Union[_ET, List[_ET]]) -> str:
488489

489490
class CsvListSerializer(ListSerializer[str]):
490491

491-
def serialize(self, value: List[str]) -> str:
492+
def serialize(self, value: list[str]) -> str:
492493
"""Serializes a list as a CSV string or unicode."""
493494
output = io.StringIO()
494495
writer = csv.writer(output, delimiter=self.list_sep)
@@ -528,16 +529,14 @@ class BaseListParser(ArgumentParser):
528529
of the separator.
529530
"""
530531

531-
def __init__(
532-
self, token: Optional[str] = None, name: Optional[str] = None
533-
) -> None:
532+
def __init__(self, token: str | None = None, name: str | None = None) -> None:
534533
assert name
535534
super().__init__()
536535
self._token = token
537536
self._name = name
538537
self.syntactic_help = 'a %s separated list' % self._name
539538

540-
def parse(self, argument: str) -> List[str]:
539+
def parse(self, argument: str) -> list[str]:
541540
"""See base class."""
542541
if isinstance(argument, list):
543542
return argument
@@ -557,7 +556,7 @@ class ListParser(BaseListParser):
557556
def __init__(self) -> None:
558557
super().__init__(',', 'comma')
559558

560-
def parse(self, argument: Union[str, List[str]]) -> List[str]:
559+
def parse(self, argument: str | list[str]) -> list[str]:
561560
"""Parses argument as comma-separated list of strings."""
562561
if isinstance(argument, list):
563562
return argument
@@ -577,7 +576,7 @@ def parse(self, argument: Union[str, List[str]]) -> List[str]:
577576

578577
def _custom_xml_dom_elements(
579578
self, doc: minidom.Document
580-
) -> List[minidom.Element]:
579+
) -> list[minidom.Element]:
581580
elements = super()._custom_xml_dom_elements(doc)
582581
elements.append(_helpers.create_xml_dom_element(
583582
doc, 'list_separator', repr(',')))
@@ -599,7 +598,7 @@ def __init__(self, comma_compat: bool = False) -> None:
599598
name = 'whitespace or comma' if self._comma_compat else 'whitespace'
600599
super().__init__(None, name)
601600

602-
def parse(self, argument: Union[str, List[str]]) -> List[str]:
601+
def parse(self, argument: str | list[str]) -> list[str]:
603602
"""Parses argument as whitespace-separated list of strings.
604603
605604
It also parses argument as comma-separated list of strings if requested.
@@ -621,7 +620,7 @@ def parse(self, argument: Union[str, List[str]]) -> List[str]:
621620

622621
def _custom_xml_dom_elements(
623622
self, doc: minidom.Document
624-
) -> List[minidom.Element]:
623+
) -> list[minidom.Element]:
625624
elements = super()._custom_xml_dom_elements(doc)
626625
separators = list(string.whitespace)
627626
if self._comma_compat:

0 commit comments

Comments
 (0)