Skip to content

Commit ae5b877

Browse files
committed
Replace Optional: part 1, no nesting
1 parent 93e4bec commit ae5b877

31 files changed

+264
-270
lines changed

bin/cleanup/cleanup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ def cleanup_client(
379379
gcp_api_manager,
380380
gcp_service_account,
381381
*,
382-
suffix: Optional[str] = "",
382+
suffix: str | None = "",
383383
):
384384
deployment_name = xds_flags.CLIENT_NAME.value
385385
if suffix:
@@ -422,7 +422,7 @@ def cleanup_server(
422422
gcp_api_manager,
423423
gcp_service_account,
424424
*,
425-
suffix: Optional[str] = "",
425+
suffix: str | None = "",
426426
):
427427
deployment_name = xds_flags.SERVER_NAME.value
428428
if suffix:
@@ -563,7 +563,7 @@ def delete_k8s_resources(
563563

564564
def _rule_match_k8s_namespace(
565565
namespace_name: str, k8s_resource_rules: List[K8sResourceRule]
566-
) -> Optional[K8sResourceRule]:
566+
) -> K8sResourceRule | None:
567567
for rule in k8s_resource_rules:
568568
result = re.search(rule.expression, namespace_name)
569569
if result is not None:

framework/bootstrap_generator_testcase.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def initTrafficDirectorManager(cls) -> TrafficDirectorManager:
127127

128128
@classmethod
129129
def initKubernetesServerRunner(
130-
cls, *, td_bootstrap_image: Optional[str] = None
130+
cls, *, td_bootstrap_image: str | None = None
131131
) -> KubernetesServerRunner:
132132
if not td_bootstrap_image:
133133
td_bootstrap_image = cls.td_bootstrap_image
@@ -165,7 +165,7 @@ def startTestServer(
165165
return test_server
166166

167167
def initKubernetesClientRunner(
168-
self, td_bootstrap_image: Optional[str] = None
168+
self, td_bootstrap_image: str | None = None
169169
) -> KubernetesClientRunner:
170170
if not td_bootstrap_image:
171171
td_bootstrap_image = self.td_bootstrap_image

framework/helpers/datetime.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def datetime_suffix(*, seconds: bool = False) -> str:
5757
return utc_now().strftime("%Y%m%d-%H%M" + ("%S" if seconds else ""))
5858

5959

60-
def ago(date_from: datetime.datetime, now: Optional[datetime.datetime] = None):
60+
def ago(date_from: datetime.datetime, now: datetime.datetime | None = None):
6161
if not now:
6262
now = utc_now()
6363

framework/helpers/grpc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232

3333
@functools.cache
34-
def status_from_int(grpc_status_int: int) -> Optional[grpc.StatusCode]:
34+
def status_from_int(grpc_status_int: int) -> grpc.StatusCode | None:
3535
"""Converts the integer gRPC status code to the grpc.StatusCode enum."""
3636
for grpc_status in grpc.StatusCode:
3737
if grpc_status.value[0] == grpc_status_int:
@@ -77,7 +77,7 @@ def from_response(
7777
) -> "PrettyStatsPerMethod":
7878
stats: dict[str, int] = dict()
7979
for status_int, count in method_stats.result.items():
80-
status: Optional[grpc.StatusCode] = status_from_int(status_int)
80+
status: grpc.StatusCode | None = status_from_int(status_int)
8181
status_formatted = status_pretty(status) if status else "None"
8282
stats[status_formatted] = count
8383
return PrettyStatsPerMethod(

framework/helpers/highlighter.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,14 @@ class Highlighter:
6363
formatter: Formatter
6464
lexer: Lexer
6565
color: bool
66-
color_style: Optional[str] = None
66+
color_style: str | None = None
6767

6868
def __init__(
6969
self,
7070
*,
7171
lexer: Lexer,
72-
color: Optional[bool] = None,
73-
color_style: Optional[str] = None,
72+
color: bool | None = None,
73+
color_style: str | None = None,
7474
):
7575
self.lexer = lexer
7676
self.color = color if color is not None else COLOR.value
@@ -97,7 +97,7 @@ def highlight(self, code: str) -> str:
9797

9898
class HighlighterYaml(Highlighter):
9999
def __init__(
100-
self, *, color: Optional[bool] = None, color_style: Optional[str] = None
100+
self, *, color: bool | None = None, color_style: str | None = None
101101
):
102102
super().__init__(
103103
lexer=YamlLexer(encoding="utf-8"),

framework/helpers/retryers.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@
4141

4242
def _build_retry_conditions(
4343
*,
44-
retry_on_exceptions: Optional[_ExceptionClasses] = None,
45-
check_result: Optional[CheckResultFn] = None,
44+
retry_on_exceptions: _ExceptionClasses | None = None,
45+
check_result: CheckResultFn | None = None,
4646
) -> List[retry_base]:
4747
# Retry on all exceptions by default
4848
if retry_on_exceptions is None:
@@ -63,10 +63,10 @@ def exponential_retryer_with_timeout(
6363
wait_min: timedelta,
6464
wait_max: timedelta,
6565
timeout: timedelta,
66-
retry_on_exceptions: Optional[_ExceptionClasses] = None,
67-
check_result: Optional[CheckResultFn] = None,
68-
logger: Optional[logging.Logger] = None,
69-
log_level: Optional[int] = logging.DEBUG,
66+
retry_on_exceptions: _ExceptionClasses | None = None,
67+
check_result: CheckResultFn | None = None,
68+
logger: logging.Logger | None = None,
69+
log_level: int | None = logging.DEBUG,
7070
error_note: str = "",
7171
) -> Retrying:
7272
if logger is None:
@@ -95,11 +95,11 @@ def constant_retryer(
9595
*,
9696
wait_fixed: timedelta,
9797
attempts: int = 0,
98-
timeout: Optional[timedelta] = None,
99-
retry_on_exceptions: Optional[_ExceptionClasses] = None,
100-
check_result: Optional[CheckResultFn] = None,
101-
logger: Optional[logging.Logger] = None,
102-
log_level: Optional[int] = logging.DEBUG,
98+
timeout: timedelta | None = None,
99+
retry_on_exceptions: _ExceptionClasses | None = None,
100+
check_result: CheckResultFn | None = None,
101+
logger: logging.Logger | None = None,
102+
log_level: int | None = logging.DEBUG,
103103
error_note: str = "",
104104
) -> Retrying:
105105
if logger is None:
@@ -134,9 +134,9 @@ def constant_retryer(
134134

135135
def _on_error_callback(
136136
*,
137-
timeout: Optional[timedelta] = None,
137+
timeout: timedelta | None = None,
138138
attempts: int = 0,
139-
check_result: Optional[CheckResultFn] = None,
139+
check_result: CheckResultFn | None = None,
140140
error_note: str = "",
141141
):
142142
"""A helper to propagate the initial state to the RetryError, so that
@@ -234,9 +234,9 @@ def __init__(
234234
self,
235235
retry_state,
236236
*,
237-
timeout: Optional[timedelta] = None,
237+
timeout: timedelta | None = None,
238238
attempts: int = 0,
239-
check_result: Optional[CheckResultFn] = None,
239+
check_result: CheckResultFn | None = None,
240240
note: str = "",
241241
):
242242
last_attempt: tenacity.Future = retry_state.outcome
@@ -292,7 +292,7 @@ def reason_str(self):
292292
return self.exception_str() if self.exception() else self.result_str()
293293

294294
@classmethod
295-
def _exception_str(cls, err: Optional[BaseException]) -> str:
295+
def _exception_str(cls, err: BaseException | None) -> str:
296296
return f"{type(err).__name__}: {err}" if err else "???"
297297

298298
# TODO(sergiitk): Remove in py3.11, this will be built-in. See PEP 678.

framework/helpers/skips.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class TestConfig:
5151

5252
client_lang: Lang
5353
server_lang: Lang
54-
version: Optional[str]
54+
version: str | None
5555

5656
def version_gte(self, another: str) -> bool:
5757
"""Returns a bool for whether this VERSION is >= then ANOTHER version.

framework/infrastructure/gcp/api.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888

8989
class GcpApiManager:
9090
# The previous value of googleapiclient.model.dump_request_response.
91-
_dump_req_resp: Optional[bool] = None
91+
_dump_req_resp: bool | None = None
9292

9393
def __init__(
9494
self,
@@ -263,8 +263,8 @@ def _build_from_discovery_v2(
263263
api_name,
264264
version,
265265
*,
266-
api_key: Optional[str] = None,
267-
visibility_labels: Optional[List] = None,
266+
api_key: str | None = None,
267+
visibility_labels: List | None = None,
268268
):
269269
params = {}
270270
if api_key:
@@ -305,8 +305,8 @@ class ResponseError(Error):
305305

306306
reason: str
307307
uri: str
308-
error_details: Optional[str]
309-
status: Optional[int]
308+
error_details: str | None
309+
status: int | None
310310
cause: _HttpError
311311

312312
def __init__(self, cause: _HttpError):
@@ -441,7 +441,7 @@ def _execute(
441441
self,
442442
request: HttpRequest,
443443
*,
444-
num_retries: Optional[int] = _GCP_API_RETRIES,
444+
num_retries: int | None = _GCP_API_RETRIES,
445445
) -> Dict[str, Any]:
446446
"""Execute the immediate request.
447447
@@ -515,7 +515,7 @@ def wait_for_operation(
515515
class GcpStandardCloudApiResource(GcpProjectApiResource, metaclass=abc.ABCMeta):
516516
GLOBAL_LOCATION = "global"
517517

518-
def parent(self, location: Optional[str] = GLOBAL_LOCATION):
518+
def parent(self, location: str | None = GLOBAL_LOCATION):
519519
if location is None:
520520
location = self.GLOBAL_LOCATION
521521
return f"projects/{self.project}/locations/{location}"

framework/infrastructure/gcp/compute.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class ComputeV1(
3838
_WAIT_FOR_BACKEND_SEC = 60 * 10
3939
_WAIT_FOR_BACKEND_SLEEP_SEC = 4
4040
_WAIT_FOR_OPERATION_SEC = 60 * 10
41-
gfe_debug_header: Optional[str]
41+
gfe_debug_header: str | None
4242

4343
@dataclasses.dataclass(frozen=True)
4444
class GcpResource:
@@ -60,7 +60,7 @@ def __init__(
6060
self,
6161
api_manager: gcp.api.GcpApiManager,
6262
project: str,
63-
gfe_debug_header: Optional[str] = None,
63+
gfe_debug_header: str | None = None,
6464
version: str = "v1",
6565
):
6666
super().__init__(api_manager.compute(version), project)
@@ -80,7 +80,7 @@ def create_health_check(
8080
name: str,
8181
protocol: HealthCheckProtocol,
8282
*,
83-
port: Optional[int] = None,
83+
port: int | None = None,
8484
) -> "GcpResource":
8585
if protocol is self.HealthCheckProtocol.TCP:
8686
health_check_field = "tcpHealthCheck"
@@ -117,7 +117,7 @@ def create_firewall_rule(
117117
network_url: str,
118118
source_ranges: List[str],
119119
ports: List[str],
120-
) -> Optional["GcpResource"]:
120+
) -> "GcpResource" | None:
121121
try:
122122
return self._insert_resource(
123123
self.api.firewalls(),
@@ -146,11 +146,11 @@ def create_backend_service_traffic_director(
146146
self,
147147
name: str,
148148
health_check: "GcpResource",
149-
affinity_header: Optional[str] = None,
150-
protocol: Optional[BackendServiceProtocol] = None,
151-
subset_size: Optional[int] = None,
149+
affinity_header: str | None = None,
150+
protocol: BackendServiceProtocol | None = None,
151+
subset_size: int | None = None,
152152
locality_lb_policies: Optional[List[dict]] = None,
153-
outlier_detection: Optional[dict] = None,
153+
outlier_detection: dict | None = None,
154154
enable_dualstack: bool = False,
155155
) -> "GcpResource":
156156
if not isinstance(protocol, self.BackendServiceProtocol):
@@ -201,7 +201,7 @@ def backend_service_patch_backends(
201201
self,
202202
backend_service,
203203
backends,
204-
max_rate_per_endpoint: Optional[int] = None,
204+
max_rate_per_endpoint: int | None = None,
205205
*,
206206
circuit_breakers: Optional[dict[str, int]] = None,
207207
):
@@ -244,7 +244,7 @@ def create_url_map(
244244
matcher_name: str,
245245
src_hosts,
246246
dst_default_backend_service: "GcpResource",
247-
dst_host_rule_match_backend_service: Optional["GcpResource"] = None,
247+
dst_host_rule_match_backend_service: "GcpResource" | None = None,
248248
) -> "GcpResource":
249249
if dst_host_rule_match_backend_service is None:
250250
dst_host_rule_match_backend_service = dst_default_backend_service

framework/infrastructure/gcp/iam.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ class Binding:
131131

132132
role: str
133133
members: FrozenSet[str]
134-
condition: Optional[Expr] = None
134+
condition: Expr | None = None
135135

136136
@classmethod
137137
def from_response(cls, response: Dict[str, Any]) -> "Policy.Binding":
@@ -155,12 +155,12 @@ def as_dict(self) -> Dict[str, Any]:
155155

156156
bindings: FrozenSet[Binding]
157157
etag: str
158-
version: Optional[int] = None
158+
version: int | None = None
159159

160160
@functools.lru_cache(maxsize=128)
161161
def find_binding_for_role(
162-
self, role: str, condition: Optional[Expr] = None
163-
) -> Optional["Policy.Binding"]:
162+
self, role: str, condition: Expr | None = None
163+
) -> "Policy.Binding" | None:
164164
results = (
165165
binding
166166
for binding in self.bindings
@@ -283,7 +283,7 @@ def add_service_account_iam_policy_binding(
283283
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy
284284
"""
285285
policy: Policy = self.get_service_account_iam_policy(account)
286-
binding: Optional[Policy.Binding] = policy.find_binding_for_role(role)
286+
binding: Policy.Binding | None = policy.find_binding_for_role(role)
287287
if binding and member in binding.members:
288288
logger.debug(
289289
"Member %s already has role %s for Service Account %s",
@@ -325,7 +325,7 @@ def remove_service_account_iam_policy_binding(
325325
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy
326326
"""
327327
policy: Policy = self.get_service_account_iam_policy(account)
328-
binding: Optional[Policy.Binding] = policy.find_binding_for_role(role)
328+
binding: Policy.Binding | None = policy.find_binding_for_role(role)
329329

330330
if binding is None:
331331
logger.debug(

0 commit comments

Comments
 (0)