Skip to content

Commit 9381e41

Browse files
committed
refactor: use the more modern | notation in type hints
Signed-off-by: Gaëtan Lehmann <gaetan.lehmann@vates.tech>
1 parent 949628c commit 9381e41

File tree

11 files changed

+62
-64
lines changed

11 files changed

+62
-64
lines changed

lib/basevm.py

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

33
import logging
44

5-
from typing import TYPE_CHECKING, List, Literal, Optional, overload
5+
from typing import TYPE_CHECKING, List, Literal, overload
66

77
if TYPE_CHECKING:
88
from lib.host import Host
@@ -22,17 +22,17 @@ def __init__(self, uuid: str, host: Host):
2222
self.host = host
2323

2424
@overload
25-
def param_get(self, param_name: str, key: Optional[str] = ...,
25+
def param_get(self, param_name: str, key: str | None = ...,
2626
accept_unknown_key: Literal[False] = ...) -> str:
2727
...
2828

2929
@overload
30-
def param_get(self, param_name: str, key: Optional[str] = ...,
31-
accept_unknown_key: Literal[True] = ...) -> Optional[str]:
30+
def param_get(self, param_name: str, key: str | None = ...,
31+
accept_unknown_key: Literal[True] = ...) -> str | None:
3232
...
3333

34-
def param_get(self, param_name: str, key: Optional[str] = None,
35-
accept_unknown_key: bool = False) -> Optional[str]:
34+
def param_get(self, param_name: str, key: str | None = None,
35+
accept_unknown_key: bool = False) -> str | None:
3636
return _param_get(self.host, self.xe_prefix, self.uuid,
3737
param_name, key, accept_unknown_key)
3838

@@ -61,7 +61,7 @@ def name(self) -> str:
6161
def _disk_list(self) -> str:
6262
raise NotImplementedError()
6363

64-
def vdi_uuids(self, sr_uuid: Optional[str] = None) -> List[str]:
64+
def vdi_uuids(self, sr_uuid: str | None = None) -> List[str]:
6565
output = self._disk_list()
6666
if output == '':
6767
return []

lib/commands.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import lib.config as config
1010
from lib.netutil import wrap_ip
1111

12-
from typing import TYPE_CHECKING, List, Literal, Union, overload
12+
from typing import TYPE_CHECKING, List, Literal, overload
1313

1414
if TYPE_CHECKING:
1515
from lib.common import HostAddress
@@ -137,7 +137,7 @@ def _ssh(
137137
if res.returncode == 255:
138138
return SSHCommandFailed(255, "SSH Error: %s" % output_for_errors, cmd)
139139

140-
output: Union[bytes, str] = res.stdout
140+
output: str | bytes = res.stdout
141141
if banner_res:
142142
if banner_res.returncode == 255:
143143
return SSHCommandFailed(255, "SSH Error: %s" % banner_res.stdout.decode(errors='replace'), cmd)
@@ -186,7 +186,7 @@ def ssh(hostname_or_ip: HostAddress, cmd: str, *, check: bool = True,
186186
simple_output: bool = True,
187187
suppress_fingerprint_warnings: bool = True, background: bool = False,
188188
decode: bool = True, options: List[str] = [], multiplexing: bool = True) \
189-
-> Union[str, bytes, SSHResult, None]:
189+
-> str | bytes | SSHResult | None:
190190
...
191191
def ssh(hostname_or_ip: HostAddress, cmd: str, *, check: bool = True, simple_output: bool = True,
192192
suppress_fingerprint_warnings: bool = True,

lib/common.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,8 @@
2525
Any,
2626
Callable,
2727
Literal,
28-
Optional,
2928
TypeAlias,
3029
TypeVar,
31-
Union,
3230
cast,
3331
overload,
3432
)
@@ -134,7 +132,7 @@ def ensure_type(tp: Any, v: object) -> Any:
134132
"""
135133
return _get_type_adapter(tp).validate_python(v)
136134

137-
def callable_marker(value: Union[T, Callable[..., T]], request: pytest.FixtureRequest) -> T:
135+
def callable_marker(value: T | Callable[..., T], request: pytest.FixtureRequest) -> T:
138136
"""
139137
Process value optionally generated by fixture-dependent callable.
140138
@@ -304,22 +302,22 @@ def randid(length: int = 6) -> str:
304302
return ''.join(random.choices(characters, k=length))
305303

306304
@overload
307-
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: Optional[str] = ...,
305+
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: str | None = ...,
308306
accept_unknown_key: Literal[False] = ...) -> str:
309307
...
310308

311309
@overload
312-
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: Optional[str] = ...,
313-
accept_unknown_key: Literal[True] = ...) -> Optional[str]:
310+
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: str | None = ...,
311+
accept_unknown_key: Literal[True] = ...) -> str | None:
314312
...
315313

316314
@overload
317-
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: Optional[str] = ...,
318-
accept_unknown_key: bool = ...) -> Optional[str]:
315+
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: str | None = ...,
316+
accept_unknown_key: bool = ...) -> str | None:
319317
...
320318

321-
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: Optional[str] = None,
322-
accept_unknown_key: bool = False) -> Optional[str]:
319+
def _param_get(host: Host, xe_prefix: str, uuid: str, param_name: str, key: str | None = None,
320+
accept_unknown_key: bool = False) -> str | None:
323321
""" Common implementation for param_get. """
324322
import lib.commands as commands
325323
args: dict[str, str | bool | dict[str, str]] = {'uuid': uuid, 'param-name': param_name}

lib/efi.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
import lib.commands as commands
2323

24-
from typing import Any, Iterable, Literal, Optional, Self, Union, cast
24+
from typing import Any, Iterable, Literal, Self, cast
2525

2626
class _EfiGlobalTempdir:
2727
_instance = None
@@ -230,7 +230,7 @@ def certs_to_sig_db(certs: list[str] | str) -> bytes:
230230

231231

232232
def sign_efi_sig_db(
233-
sig_db: bytes, var: str, key: str, cert: str, time: Optional[datetime] = None, guid: Optional[GUID] = None
233+
sig_db: bytes, var: str, key: str, cert: str, time: datetime | None = None, guid: GUID | None = None
234234
) -> bytes:
235235
"""Return a pkcs7 SignedData from a UEFI signature database."""
236236
global p7_out
@@ -363,7 +363,7 @@ def pesign(key: str, cert: str, name: str, image: str) -> str:
363363

364364

365365
class Certificate:
366-
def __init__(self, pub: str, key: Optional[str]):
366+
def __init__(self, pub: str, key: str | None) -> None:
367367
self.pub = pub
368368
self.key = key
369369

@@ -397,15 +397,15 @@ def copy(self) -> Certificate:
397397

398398

399399
class EFIAuth:
400-
_auth_data: Optional[bytes]
400+
_auth_data: bytes | None
401401
name: Literal["PK", "KEK", "db", "dbx"]
402402

403403
def __init__(
404404
self,
405405
name: Literal["PK", "KEK", "db", "dbx"],
406-
owner_cert: Optional[Certificate] = None,
407-
other_certs: Optional[Iterable[Union[Certificate, str]]] = None,
408-
):
406+
owner_cert: Certificate | None = None,
407+
other_certs: Iterable[Certificate | str] | None = None,
408+
) -> None:
409409
assert name in SECURE_BOOT_VARIABLES
410410
assert owner_cert is None or owner_cert.key is not None, "owner cert must have private key"
411411
self.name = name
@@ -418,7 +418,7 @@ def __init__(
418418

419419
@classmethod
420420
def self_signed(
421-
cls, name: Literal["PK", "KEK", "db", "dbx"], other_certs: Optional[Iterable[Union[Certificate, str]]] = None
421+
cls, name: Literal["PK", "KEK", "db", "dbx"], other_certs: Iterable[Certificate | str] | None = None
422422
) -> Self:
423423
return cls(name, owner_cert=Certificate.self_signed(name + " Owner"), other_certs=other_certs)
424424

lib/host.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from lib.vm import VM
3232
from lib.xo import xo_cli, xo_object_exists
3333

34-
from typing import TYPE_CHECKING, Literal, Optional, TypedDict, Union, cast, overload
34+
from typing import TYPE_CHECKING, Literal, TypedDict, cast, overload
3535

3636
if TYPE_CHECKING:
3737
from lib.pool import Pool
@@ -52,7 +52,7 @@ def host_data(hostname_or_ip: str) -> dict[str, str]:
5252

5353
class Host:
5454
xe_prefix = "host"
55-
pool: Pool
55+
pool: "Pool"
5656

5757
# Data extraction is automatic, no conversion from str is done.
5858
BlockDeviceInfo = TypedDict('BlockDeviceInfo', {"name": str,
@@ -69,7 +69,7 @@ class Host:
6969
def __init__(self, pool: Pool, hostname_or_ip: str):
7070
self.pool = pool
7171
self.hostname_or_ip = hostname_or_ip
72-
self.xo_srv_id: Optional[str] = None
72+
self.xo_srv_id: str | None = None
7373

7474
h_data = host_data(self.hostname_or_ip)
7575
self.user = h_data['user']
@@ -82,7 +82,7 @@ def __init__(self, pool: Pool, hostname_or_ip: str):
8282
self.uuid = self.inventory['INSTALLATION_UUID']
8383
self.xcp_version = version.parse(self.inventory['PRODUCT_VERSION'])
8484
self.xcp_version_short = f"{self.xcp_version.major}.{self.xcp_version.minor}"
85-
self._dom0: Optional[VM] = None
85+
self._dom0: VM | None = None
8686

8787
self.rescan_block_devices_info()
8888

@@ -117,7 +117,7 @@ def ssh(self, cmd: str, *, check: bool = True, simple_output: bool = True,
117117
def ssh(self, cmd: str, *, check: bool = True, simple_output: bool = True,
118118
suppress_fingerprint_warnings: bool = True, background: bool = False, decode: bool = True,
119119
multiplexing: bool = True) \
120-
-> Union[str, bytes, commands.SSHResult, None]:
120+
-> str | bytes | commands.SSHResult | None:
121121
...
122122

123123
def ssh(self, cmd: str, *, check: bool = True, simple_output: bool = True,
@@ -150,7 +150,7 @@ def xe(self, action: str, args: dict[str, str | bool | dict[str, str]] = {}, *,
150150

151151
def xe(self, action: str, args: dict[str, str | bool | dict[str, str]] = {}, *, check: bool = True,
152152
simple_output: bool = True, minimal: bool = False, force: bool = False) \
153-
-> Union[str, commands.SSHResult]:
153+
-> str | commands.SSHResult:
154154
maybe_param_minimal = '--minimal' if minimal else ''
155155
maybe_param_force = '--force' if force else ''
156156

@@ -176,16 +176,16 @@ def stringify(key: str, value: str | bool | dict[str, str]) -> str:
176176
return result
177177

178178
@overload
179-
def param_get(self, param_name: str, key: Optional[str] = ...,
179+
def param_get(self, param_name: str, key: str | None = ...,
180180
accept_unknown_key: Literal[False] = ...) -> str:
181181
...
182182

183183
@overload
184-
def param_get(self, param_name: str, key: Optional[str] = ...,
185-
accept_unknown_key: Literal[True] = ...) -> Optional[str]:
184+
def param_get(self, param_name: str, key: str | None = ...,
185+
accept_unknown_key: Literal[True] = ...) -> str | None:
186186
...
187187

188-
def param_get(self, param_name: str, key: Optional[str] = None, accept_unknown_key: bool = False) -> Optional[str]:
188+
def param_get(self, param_name: str, key: str | None = None, accept_unknown_key: bool = False) -> str | None:
189189
return _param_get(self, self.xe_prefix, self.uuid,
190190
param_name, key, accept_unknown_key)
191191

@@ -358,8 +358,8 @@ def cached_vm(self, uri: str, sr_uuid: str) -> VM | None:
358358
logging.info("Could not find a VM in cache for %r", uri)
359359
return None
360360

361-
def import_vm(self, uri: str, sr_uuid: str | None = None, use_cache: bool = False) -> "VM":
362-
vm = None
361+
def import_vm(self, uri: str, sr_uuid: str | None = None, use_cache: bool = False) -> VM:
362+
vm: VM | None = None
363363
if use_cache:
364364
assert sr_uuid is not None
365365
if '://' in uri and uri.startswith("clone"):
@@ -772,7 +772,7 @@ def get_dom0_vm(self) -> VM:
772772
self._dom0 = VM(self.get_dom0_uuid(), self)
773773
return self._dom0
774774

775-
def get_sr_from_vdi_uuid(self, vdi_uuid: str) -> Optional[SR]:
775+
def get_sr_from_vdi_uuid(self, vdi_uuid: str) -> SR | None:
776776
sr_uuid = self.xe("vdi-param-get", {
777777
"param-name": "sr-uuid",
778778
"uuid": vdi_uuid,

lib/pool.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from lib.host import Host
1313
from lib.sr import SR
1414

15-
from typing import Any, Callable, Iterable, Optional
15+
from typing import Any, Callable, Iterable
1616

1717
class Pool:
1818
xe_prefix = "pool"
@@ -111,13 +111,13 @@ def get_host_by_uuid(self, host_uuid: str) -> Host:
111111
return host
112112
raise Exception(f"Host with uuid {host_uuid} not found in pool.")
113113

114-
def first_host_that_isnt(self, host: Host) -> Optional[Host]:
114+
def first_host_that_isnt(self, host: Host) -> Host | None:
115115
for h in self.hosts:
116116
if h != host:
117117
return h
118118
return None
119119

120-
def first_shared_sr(self) -> Optional[SR]:
120+
def first_shared_sr(self) -> SR | None:
121121
uuids = safe_split(self.master.xe('sr-list', {'shared': True, 'content-type': 'user'}, minimal=True))
122122
if len(uuids) > 0:
123123
return SR(uuids[0], self)

lib/sr.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
)
1616
from lib.vdi import VDI, ImageFormat
1717

18-
from typing import TYPE_CHECKING, Optional
18+
from typing import TYPE_CHECKING
1919

2020
if TYPE_CHECKING:
2121
from lib.host import Host
@@ -25,9 +25,9 @@ class SR:
2525
def __init__(self, uuid: str, pool: Pool):
2626
self.uuid = uuid
2727
self.pool = pool
28-
self._is_shared: Optional[bool] = None # cached value for is_shared()
29-
self._main_host: Optional[Host] = None # cached value for main_host()
30-
self._type: Optional[str] = None # cache value for get_type()
28+
self._is_shared: bool | None = None # cached value for is_shared()
29+
self._main_host: Host | None = None # cached value for main_host()
30+
self._type: str | None = None # cache value for get_type()
3131

3232
def pbd_uuids(self) -> list[str]:
3333
return safe_split(self.pool.master.xe('pbd-list', {'sr-uuid': self.uuid}, minimal=True))

lib/vdi.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
wait_for_not,
1414
)
1515

16-
from typing import TYPE_CHECKING, Callable, Literal, Optional, TypeVar, overload
16+
from typing import TYPE_CHECKING, Callable, Literal, TypeVar, overload
1717

1818
if TYPE_CHECKING:
1919
from lib.host import Host
@@ -74,7 +74,7 @@ def resize(self, new_size: int) -> None:
7474
def __str__(self) -> str:
7575
return f"VDI {self.uuid} on SR {self.sr.uuid}"
7676

77-
def get_parent(self) -> Optional[str]:
77+
def get_parent(self) -> str | None:
7878
return self.param_get("sm-config", key="vhd-parent", accept_unknown_key=True)
7979

8080
def get_image_format(self) -> ImageFormat | None:
@@ -84,17 +84,17 @@ def get_image_format(self) -> ImageFormat | None:
8484
return ensure_type(ImageFormat, v)
8585

8686
@overload
87-
def param_get(self, param_name: str, key: Optional[str] = ...,
87+
def param_get(self, param_name: str, key: str | None = ...,
8888
accept_unknown_key: Literal[False] = ...) -> str:
8989
...
9090

9191
@overload
92-
def param_get(self, param_name: str, key: Optional[str] = ...,
93-
accept_unknown_key: Literal[True] = ...) -> Optional[str]:
92+
def param_get(self, param_name: str, key: str | None = ...,
93+
accept_unknown_key: Literal[True] = ...) -> str | None:
9494
...
9595

96-
def param_get(self, param_name: str, key: Optional[str] = None,
97-
accept_unknown_key: bool = False) -> Optional[str]:
96+
def param_get(self, param_name: str, key: str | None = None,
97+
accept_unknown_key: bool = False) -> str | None:
9898
return _param_get(self.sr.pool.master, self.xe_prefix, self.uuid,
9999
param_name, key, accept_unknown_key)
100100

@@ -116,7 +116,7 @@ def param_remove(self, param_name: str, key: str, accept_unknown_key: bool = Fal
116116

117117
def wait_for_coalesce(self, fn: Callable[[], R] | None = None) -> R | None:
118118
previous_parent = self.get_parent()
119-
ret = None
119+
ret: R | None = None
120120
if fn is not None:
121121
ret = fn()
122122
# It is necessary to wait a long time because the GC can be paused for more than 5 minutes.

lib/vm.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,16 @@
2727
from lib.vdi import VDI
2828
from lib.vif import VIF
2929

30-
from typing import TYPE_CHECKING, Iterable, List, Literal, Optional, cast, overload
30+
from typing import TYPE_CHECKING, Iterable, List, Literal, cast, overload
3131

3232
if TYPE_CHECKING:
3333
from lib.host import Host
3434

3535
class VM(BaseVM):
36-
def __init__(self, uuid: str, host: Host):
36+
def __init__(self, uuid: str, host: Host) -> None:
3737
super().__init__(uuid, host)
38-
self.ip: Optional[str] = None
39-
self.previous_host: Optional[Host] = None # previous host when migrated or being migrated
38+
self.ip: str | None = None
39+
self.previous_host: Host | None = None # previous host when migrated or being migrated
4040
self.is_windows = self.param_get('platform', 'device_id', accept_unknown_key=True) == '0002'
4141
self.is_uefi = self.param_get('HVM-boot-params', 'firmware', accept_unknown_key=True) == 'uefi'
4242
self.create_vdis_list()

0 commit comments

Comments
 (0)