Skip to content

Commit c59c8dd

Browse files
Merge pull request #541 from dklimpel/use_mypy
misc: add mypy for type checking
2 parents f8c799c + adb33a4 commit c59c8dd

File tree

15 files changed

+91
-35
lines changed

15 files changed

+91
-35
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v2.3.0
3+
rev: v5.0.0
44
hooks:
55
- id: check-yaml
66
exclude: "gating.yml"
@@ -19,3 +19,9 @@ repos:
1919
rev: 1.39.0
2020
hooks:
2121
- id: tmt-lint
22+
- repo: https://github.com/pre-commit/mirrors-mypy
23+
rev: v1.15.0
24+
hooks:
25+
- id: mypy
26+
pass_filenames: false
27+
args: ["--package", "podman"]

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ podman:
1919

2020
.PHONY: lint
2121
lint: tox
22-
$(PYTHON) -m tox -e format,lint
22+
$(PYTHON) -m tox -e format,lint,mypy
2323

2424
.PHONY: tests
2525
tests: tox

podman/api/cached_property.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@
66
from functools import cached_property # pylint: disable=unused-import
77
except ImportError:
88

9-
def cached_property(fn):
9+
def cached_property(fn): # type: ignore[no-redef]
1010
return property(functools.lru_cache()(fn))

podman/api/http_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ def _filter_values(mapping: Mapping[str, Any], recursion=False) -> dict[str, Any
8585
continue
8686

8787
# depending on type we need details...
88+
proposal: Any
8889
if isinstance(value, collections.abc.Mapping):
8990
proposal = _filter_values(value, recursion=True)
9091
elif isinstance(value, collections.abc.Iterable) and not isinstance(value, str):
@@ -100,5 +101,5 @@ def _filter_values(mapping: Mapping[str, Any], recursion=False) -> dict[str, Any
100101
return canonical
101102

102103

103-
def encode_auth_header(auth_config: dict[str, str]) -> str:
104+
def encode_auth_header(auth_config: dict[str, str]) -> bytes:
104105
return base64.urlsafe_b64encode(json.dumps(auth_config).encode('utf-8'))

podman/api/parse_utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from typing import Any, Optional, Union
99
from collections.abc import Iterator
1010

11-
from requests import Response
11+
from podman.api.client import APIResponse
1212
from .output_utils import demux_output
1313

1414

@@ -59,15 +59,15 @@ def prepare_timestamp(value: Union[datetime, int, None]) -> Optional[int]:
5959
raise ValueError(f"Type '{type(value)}' is not supported by prepare_timestamp()")
6060

6161

62-
def prepare_cidr(value: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]) -> (str, str):
62+
def prepare_cidr(value: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]) -> tuple[str, str]:
6363
"""Returns network address and Base64 encoded netmask from CIDR.
6464
6565
The return values are dictated by the Go JSON decoder.
6666
"""
6767
return str(value.network_address), base64.b64encode(value.netmask.packed).decode("utf-8")
6868

6969

70-
def frames(response: Response) -> Iterator[bytes]:
70+
def frames(response: APIResponse) -> Iterator[bytes]:
7171
"""Returns each frame from multiplexed payload, all results are expected in the payload.
7272
7373
The stdout and stderr frames are undifferentiated as they are returned.
@@ -84,7 +84,7 @@ def frames(response: Response) -> Iterator[bytes]:
8484

8585

8686
def stream_frames(
87-
response: Response, demux: bool = False
87+
response: APIResponse, demux: bool = False
8888
) -> Iterator[Union[bytes, tuple[bytes, bytes]]]:
8989
"""Returns each frame from multiplexed streamed payload.
9090
@@ -111,7 +111,7 @@ def stream_frames(
111111

112112

113113
def stream_helper(
114-
response: Response, decode_to_json: bool = False
114+
response: APIResponse, decode_to_json: bool = False
115115
) -> Union[Iterator[bytes], Iterator[dict[str, Any]]]:
116116
"""Helper to stream results and optionally decode to json"""
117117
for value in response.iter_lines():

podman/domain/containers_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def prune(self, filters: Mapping[str, str] = None) -> dict[str, Any]:
120120
explanation=f"""Failed to prune container '{entry["Id"]}'""",
121121
)
122122

123-
results["ContainersDeleted"].append(entry["Id"])
123+
results["ContainersDeleted"].append(entry["Id"]) # type: ignore[attr-defined]
124124
results["SpaceReclaimed"] += entry["Size"]
125125
return results
126126

podman/domain/images.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Model and Manager for Image resources."""
22

33
import logging
4-
from typing import Any, Optional, Literal, Union
4+
from typing import Any, Optional, Literal, Union, TYPE_CHECKING
55
from collections.abc import Iterator
66

77
import urllib.parse
@@ -10,12 +10,17 @@
1010
from podman.domain.manager import PodmanResource
1111
from podman.errors import ImageNotFound, InvalidArgument
1212

13+
if TYPE_CHECKING:
14+
from podman.domain.images_manager import ImagesManager
15+
1316
logger = logging.getLogger("podman.images")
1417

1518

1619
class Image(PodmanResource):
1720
"""Details and configuration for an Image managed by the Podman service."""
1821

22+
manager: "ImagesManager"
23+
1924
def __repr__(self) -> str:
2025
return f"""<{self.__class__.__name__}: '{"', '".join(self.tags)}'>"""
2126

podman/domain/networks_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import ipaddress
1313
import logging
1414
from contextlib import suppress
15-
from typing import Any, Optional, Literal
15+
from typing import Any, Optional, Literal, Union
1616

1717
from podman.api import http_utils, prepare_filters
1818
from podman.domain.manager import Manager
@@ -188,7 +188,7 @@ def prune(
188188

189189
return {"NetworksDeleted": deleted, "SpaceReclaimed": 0}
190190

191-
def remove(self, name: [Network, str], force: Optional[bool] = None) -> None:
191+
def remove(self, name: Union[Network, str], force: Optional[bool] = None) -> None:
192192
"""Remove Network resource.
193193
194194
Args:

podman/domain/pods.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
"""Model and Manager for Pod resources."""
22

33
import logging
4-
from typing import Any, Optional, Union
4+
from typing import Any, Optional, Union, TYPE_CHECKING
55

66
from podman.domain.manager import PodmanResource
77

8+
if TYPE_CHECKING:
9+
from podman.domain.pods_manager import PodsManager
10+
811
_Timeout = Union[None, int, tuple[int, int], tuple[int, None]]
912

1013
logger = logging.getLogger("podman.pods")
@@ -13,6 +16,8 @@
1316
class Pod(PodmanResource):
1417
"""Details and configuration for a pod managed by the Podman service."""
1518

19+
manager: "PodsManager"
20+
1621
@property
1722
def id(self): # pylint: disable=invalid-name
1823
return self.attrs.get("ID", self.attrs.get("Id"))

podman/errors/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def __init__(self, message, response=None):
5858
from .exceptions import ImageNotFound
5959
except ImportError:
6060

61-
class ImageNotFound(NotFoundError):
61+
class ImageNotFound(NotFoundError): # type: ignore[no-redef]
6262
"""HTTP request returned a http.HTTPStatus.NOT_FOUND.
6363
6464
Specialized for Image not found. Deprecated.

0 commit comments

Comments
 (0)