Skip to content

Commit 76e5157

Browse files
committed
Fix typing issues and activate pyright strict mode
1 parent 67844f4 commit 76e5157

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+950
-831
lines changed

Diff for: .pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ repos:
1616
hooks:
1717
- id: ruff
1818
- repo: https://github.com/RobertCraigie/pyright-python
19-
rev: v1.1.385
19+
rev: v1.1.391
2020
hooks:
2121
- id: pyright
2222
name: pyright (system)

Diff for: contrib/encode_video.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import annotations
2-
31
import sys
42
from pathlib import Path
53

@@ -20,7 +18,6 @@ def encode_video(src_path: Path, dst_path: Path, preset: str):
2018
src_path=src_path,
2119
dst_path=dst_path,
2220
ffmpeg_args=preset_cls().to_ffmpeg_args(),
23-
with_process=True,
2421
) # pyright: ignore[reportGeneralTypeIssues] (returned type is variable, depending on `with_process` value)
2522
if not success:
2623
logger.error(f"conversion failed:\n{process.stdout}")

Diff for: pyproject.toml

+2-5
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ lint = [
5656
"ruff==0.8.2",
5757
]
5858
check = [
59-
"pyright==1.1.390",
59+
"pyright==1.1.391",
6060
"pytest==8.3.4",
6161
]
6262
test = [
@@ -286,12 +286,9 @@ include = ["contrib", "src", "tests", "tasks.py"]
286286
exclude = [".env/**", ".venv/**"]
287287
extraPaths = ["src"]
288288
pythonVersion = "3.12"
289-
typeCheckingMode="basic"
289+
typeCheckingMode="strict"
290290
disableBytesTypePromotions = true
291291

292-
[tool.pyright.overrides]
293-
strict = true # Enable strict mode for specific files
294-
295292
[[tool.pyright.overrides.files]]
296293
files = [
297294
"src/zimscraperlib/rewriting**/*.py",

Diff for: rules/generate_rules.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -156,11 +156,11 @@
156156
{% endfor %}
157157
]
158158
)
159-
def {{ rule['name'] }}_case(request):
159+
def {{ rule['name'] }}_case(request: pytest.FixtureRequest):
160160
yield request.param
161161
162162
163-
def test_fuzzyrules_{{ rule['name'] }}({{ rule['name'] }}_case):
163+
def test_fuzzyrules_{{ rule['name'] }}({{ rule['name'] }}_case: ContentForTests):
164164
assert (
165165
ArticleUrlRewriter.apply_additional_rules({{ rule['name'] }}_case.input_str)
166166
== {{ rule['name'] }}_case.expected_str

Diff for: src/zimscraperlib/__init__.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
#!/usr/bin/env python
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
41
import logging as stdlogging
52
import os
63

Diff for: src/zimscraperlib/constants.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
#!/usr/bin/env python3
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
41
import pathlib
52
import re
63

Diff for: src/zimscraperlib/download.py

+13-17
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
1-
#!/usr/bin/env python3
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
4-
from __future__ import annotations
5-
61
import pathlib
72
import subprocess
83
from concurrent.futures import Future, ThreadPoolExecutor
9-
from typing import ClassVar
4+
from typing import Any, ClassVar
105

116
import requests
127
import requests.adapters
138
import requests.structures
149
import urllib3.util
15-
import yt_dlp as youtube_dl
10+
import yt_dlp as youtube_dl # pyright: ignore[reportMissingTypeStubs]
1611

1712
from zimscraperlib import logger
1813
from zimscraperlib.constants import DEFAULT_WEB_REQUESTS_TIMEOUT
@@ -31,24 +26,24 @@ def __init__(self, threads: int | None = 1) -> None:
3126
def __enter__(self):
3227
return self
3328

34-
def __exit__(self, *args):
29+
def __exit__(self, *_: Any):
3530
self.shutdown()
3631

3732
def shutdown(self) -> None:
3833
"""shuts down the executor, awaiting completion"""
3934
self.executor.shutdown(wait=True)
4035

41-
def _run_youtube_dl(self, url: str, options: dict) -> None:
36+
def _run_youtube_dl(self, url: str, options: dict[str, Any]) -> None:
4237
with youtube_dl.YoutubeDL(options) as ydl:
43-
ydl.download([url])
38+
ydl.download([url]) # pyright: ignore[reportUnknownMemberType]
4439

4540
def download(
4641
self,
4742
url: str,
48-
options: dict | None,
43+
options: dict[str, Any] | None,
4944
*,
5045
wait: bool | None = True,
51-
) -> bool | Future:
46+
) -> bool | Future[Any]:
5247
"""Downloads video using initialized executor.
5348
5449
url: URL or Video ID
@@ -66,7 +61,7 @@ def download(
6661
return True
6762

6863

69-
class YoutubeConfig(dict):
64+
class YoutubeConfig(dict[str, str | bool | int | None]):
7065
options: ClassVar[dict[str, str | bool | int | None]] = {}
7166
defaults: ClassVar[dict[str, str | bool | int | None]] = {
7267
"writethumbnail": True,
@@ -82,7 +77,7 @@ class YoutubeConfig(dict):
8277
"outtmpl": "video.%(ext)s",
8378
}
8479

85-
def __init__(self, **kwargs):
80+
def __init__(self, **kwargs: str | bool | int | None):
8681
super().__init__(self, **type(self).defaults)
8782
self.update(self.options)
8883
self.update(kwargs)
@@ -92,7 +87,7 @@ def get_options(
9287
cls,
9388
target_dir: pathlib.Path | None = None,
9489
filepath: pathlib.Path | None = None,
95-
**options,
90+
**options: str | bool | int | None,
9691
):
9792
if "outtmpl" not in options:
9893
outtmpl = cls.options.get("outtmpl", cls.defaults["outtmpl"])
@@ -143,9 +138,10 @@ def save_large_file(url: str, fpath: pathlib.Path) -> None:
143138
)
144139

145140

146-
def _get_retry_adapter(
141+
def get_retry_adapter(
147142
max_retries: int | None = 5,
148143
) -> requests.adapters.BaseAdapter:
144+
"""A requests adapter to automatically retry on known HTTP status that can be"""
149145
retries = urllib3.util.retry.Retry(
150146
total=max_retries, # total number of retries
151147
connect=max_retries, # connection errors
@@ -169,7 +165,7 @@ def _get_retry_adapter(
169165
def get_session(max_retries: int | None = 5) -> requests.Session:
170166
"""Session to hold cookies and connection pool together"""
171167
session = requests.Session()
172-
session.mount("http", _get_retry_adapter(max_retries)) # tied to http and https
168+
session.mount("http", get_retry_adapter(max_retries)) # tied to http and https
173169
return session
174170

175171

Diff for: src/zimscraperlib/filesystem.py

-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
1-
#!/usr/bin/env python
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
41
""" Files manipulation tools
52
63
Shortcuts to retrieve mime type using magic"""
74

8-
from __future__ import annotations
9-
105
import os
116
import pathlib
127

Diff for: src/zimscraperlib/fix_ogvjs_dist.py

-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
1-
#!/usr/bin/env python3
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
4-
51
""" quick script to fix videojs-ogvjs so that it triggers on webm mimetype """
62

7-
from __future__ import annotations
8-
93
import logging
104
import pathlib
115
import sys

Diff for: src/zimscraperlib/html.py

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
#!/usr/bin/env python
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
41
""" Tools to work with HTML contents """
5-
from __future__ import annotations
62

73
import pathlib
84
from typing import BinaryIO, TextIO
@@ -43,9 +39,7 @@ def find_language_in(content: str | BinaryIO | TextIO, mime_type: str) -> str:
4339
for key in keylist:
4440
node = soup.find(nodename)
4541
if node:
46-
if not isinstance(node, element.Tag) or (
47-
isinstance(node, element.Tag) and not node.has_attr(key)
48-
):
42+
if not isinstance(node, element.Tag) or not node.has_attr(key):
4943
continue
5044
if (
5145
nodename == "meta"

Diff for: src/zimscraperlib/i18n.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import annotations
2-
31
import re
42

53
import babel

Diff for: src/zimscraperlib/image/__init__.py

-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
# vim: ai ts=4 sts=4 et sw=4 nu
4-
51
# flake8: noqa
62
from .conversion import convert_image
73
from .optimization import optimize_image

Diff for: src/zimscraperlib/image/conversion.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
1-
#!/usr/bin/env python3
2-
# vim: ai ts=4 sts=4 et sw=4 nu
3-
4-
from __future__ import annotations
5-
61
import io
72
import pathlib
3+
from typing import Any
84

9-
import cairosvg.svg
5+
import cairosvg.svg # pyright: ignore[reportMissingTypeStubs]
106
from PIL.Image import open as pilopen
117

128
from zimscraperlib.constants import ALPHA_NOT_SUPPORTED
@@ -54,7 +50,7 @@ def convert_svg2png(
5450
Output width and height might be specified if resize is needed.
5551
PNG background is transparent.
5652
"""
57-
kwargs = {}
53+
kwargs: dict[str, Any] = {}
5854
if isinstance(src, pathlib.Path):
5955
src = str(src)
6056
if isinstance(src, str):
@@ -66,9 +62,13 @@ def convert_svg2png(
6662
if height:
6763
kwargs["output_height"] = height
6864
if isinstance(dst, pathlib.Path):
69-
cairosvg.svg2png(write_to=str(dst), **kwargs)
65+
cairosvg.svg2png( # pyright: ignore[reportUnknownMemberType]
66+
write_to=str(dst), **kwargs
67+
)
7068
else:
71-
result = cairosvg.svg2png(**kwargs)
69+
result = cairosvg.svg2png( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
70+
**kwargs
71+
)
7272
if not isinstance(result, bytes):
7373
raise Exception(
7474
"Unexpected type returned by cairosvg.svg2png"

0 commit comments

Comments
 (0)