Skip to content

Commit

Permalink
Fix typing issues and activate pyright strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
benoit74 committed Dec 20, 2024
1 parent 67844f4 commit b137179
Show file tree
Hide file tree
Showing 67 changed files with 949 additions and 831 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ repos:
hooks:
- id: ruff
- repo: https://github.com/RobertCraigie/pyright-python
rev: v1.1.385
rev: v1.1.391
hooks:
- id: pyright
name: pyright (system)
Expand Down
3 changes: 0 additions & 3 deletions contrib/encode_video.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import annotations

import sys
from pathlib import Path

Expand All @@ -20,7 +18,6 @@ def encode_video(src_path: Path, dst_path: Path, preset: str):
src_path=src_path,
dst_path=dst_path,
ffmpeg_args=preset_cls().to_ffmpeg_args(),
with_process=True,
) # pyright: ignore[reportGeneralTypeIssues] (returned type is variable, depending on `with_process` value)
if not success:
logger.error(f"conversion failed:\n{process.stdout}")
Expand Down
7 changes: 2 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ lint = [
"ruff==0.8.2",
]
check = [
"pyright==1.1.390",
"pyright==1.1.391",
"pytest==8.3.4",
]
test = [
Expand Down Expand Up @@ -286,12 +286,9 @@ include = ["contrib", "src", "tests", "tasks.py"]
exclude = [".env/**", ".venv/**"]
extraPaths = ["src"]
pythonVersion = "3.12"
typeCheckingMode="basic"
typeCheckingMode="strict"
disableBytesTypePromotions = true

[tool.pyright.overrides]
strict = true # Enable strict mode for specific files

[[tool.pyright.overrides.files]]
files = [
"src/zimscraperlib/rewriting**/*.py",
Expand Down
4 changes: 2 additions & 2 deletions rules/generate_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,11 @@
{% endfor %}
]
)
def {{ rule['name'] }}_case(request):
def {{ rule['name'] }}_case(request: pytest.FixtureRequest):
yield request.param
def test_fuzzyrules_{{ rule['name'] }}({{ rule['name'] }}_case):
def test_fuzzyrules_{{ rule['name'] }}({{ rule['name'] }}_case: ContentForTests):
assert (
ArticleUrlRewriter.apply_additional_rules({{ rule['name'] }}_case.input_str)
== {{ rule['name'] }}_case.expected_str
Expand Down
3 changes: 0 additions & 3 deletions src/zimscraperlib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 nu

import logging as stdlogging
import os

Expand Down
3 changes: 0 additions & 3 deletions src/zimscraperlib/constants.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python3
# vim: ai ts=4 sts=4 et sw=4 nu

import pathlib
import re

Expand Down
30 changes: 13 additions & 17 deletions src/zimscraperlib/download.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
#!/usr/bin/env python3
# vim: ai ts=4 sts=4 et sw=4 nu

from __future__ import annotations

import pathlib
import subprocess
from concurrent.futures import Future, ThreadPoolExecutor
from typing import ClassVar
from typing import Any, ClassVar

import requests
import requests.adapters
import requests.structures
import urllib3.util
import yt_dlp as youtube_dl
import yt_dlp as youtube_dl # pyright: ignore[reportMissingTypeStubs]

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

def __exit__(self, *args):
def __exit__(self, *_: Any):
self.shutdown()

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

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

def download(
self,
url: str,
options: dict | None,
options: dict[str, Any] | None,
*,
wait: bool | None = True,
) -> bool | Future:
) -> bool | Future[Any]:
"""Downloads video using initialized executor.
url: URL or Video ID
Expand All @@ -66,7 +61,7 @@ def download(
return True


class YoutubeConfig(dict):
class YoutubeConfig(dict[str, str | bool | int | None]):
options: ClassVar[dict[str, str | bool | int | None]] = {}
defaults: ClassVar[dict[str, str | bool | int | None]] = {
"writethumbnail": True,
Expand All @@ -82,7 +77,7 @@ class YoutubeConfig(dict):
"outtmpl": "video.%(ext)s",
}

def __init__(self, **kwargs):
def __init__(self, **kwargs: str | bool | int | None):
super().__init__(self, **type(self).defaults)
self.update(self.options)
self.update(kwargs)
Expand All @@ -92,7 +87,7 @@ def get_options(
cls,
target_dir: pathlib.Path | None = None,
filepath: pathlib.Path | None = None,
**options,
**options: str | bool | int | None,
):
if "outtmpl" not in options:
outtmpl = cls.options.get("outtmpl", cls.defaults["outtmpl"])
Expand Down Expand Up @@ -143,9 +138,10 @@ def save_large_file(url: str, fpath: pathlib.Path) -> None:
)


def _get_retry_adapter(
def get_retry_adapter(
max_retries: int | None = 5,
) -> requests.adapters.BaseAdapter:
"""A requests adapter to automatically retry on known HTTP status that can be"""
retries = urllib3.util.retry.Retry(
total=max_retries, # total number of retries
connect=max_retries, # connection errors
Expand All @@ -169,7 +165,7 @@ def _get_retry_adapter(
def get_session(max_retries: int | None = 5) -> requests.Session:
"""Session to hold cookies and connection pool together"""
session = requests.Session()
session.mount("http", _get_retry_adapter(max_retries)) # tied to http and https
session.mount("http", get_retry_adapter(max_retries)) # tied to http and https
return session


Expand Down
5 changes: 0 additions & 5 deletions src/zimscraperlib/filesystem.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 nu

""" Files manipulation tools
Shortcuts to retrieve mime type using magic"""

from __future__ import annotations

import os
import pathlib

Expand Down
6 changes: 0 additions & 6 deletions src/zimscraperlib/fix_ogvjs_dist.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
#!/usr/bin/env python3
# vim: ai ts=4 sts=4 et sw=4 nu


""" quick script to fix videojs-ogvjs so that it triggers on webm mimetype """

from __future__ import annotations

import logging
import pathlib
import sys
Expand Down
8 changes: 1 addition & 7 deletions src/zimscraperlib/html.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 nu

""" Tools to work with HTML contents """
from __future__ import annotations

import pathlib
from typing import BinaryIO, TextIO
Expand Down Expand Up @@ -43,9 +39,7 @@ def find_language_in(content: str | BinaryIO | TextIO, mime_type: str) -> str:
for key in keylist:
node = soup.find(nodename)
if node:
if not isinstance(node, element.Tag) or (
isinstance(node, element.Tag) and not node.has_attr(key)
):
if not isinstance(node, element.Tag) or not node.has_attr(key):
continue
if (
nodename == "meta"
Expand Down
2 changes: 0 additions & 2 deletions src/zimscraperlib/i18n.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import annotations

import re

import babel
Expand Down
4 changes: 0 additions & 4 deletions src/zimscraperlib/image/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

# flake8: noqa
from .conversion import convert_image
from .optimization import optimize_image
Expand Down
18 changes: 9 additions & 9 deletions src/zimscraperlib/image/conversion.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
#!/usr/bin/env python3
# vim: ai ts=4 sts=4 et sw=4 nu

from __future__ import annotations

import io
import pathlib
from typing import Any

import cairosvg.svg
import cairosvg.svg # pyright: ignore[reportMissingTypeStubs]
from PIL.Image import open as pilopen

from zimscraperlib.constants import ALPHA_NOT_SUPPORTED
Expand Down Expand Up @@ -54,7 +50,7 @@ def convert_svg2png(
Output width and height might be specified if resize is needed.
PNG background is transparent.
"""
kwargs = {}
kwargs: dict[str, Any] = {}
if isinstance(src, pathlib.Path):
src = str(src)
if isinstance(src, str):
Expand All @@ -66,9 +62,13 @@ def convert_svg2png(
if height:
kwargs["output_height"] = height
if isinstance(dst, pathlib.Path):
cairosvg.svg2png(write_to=str(dst), **kwargs)
cairosvg.svg2png( # pyright: ignore[reportUnknownMemberType]
write_to=str(dst), **kwargs
)
else:
result = cairosvg.svg2png(**kwargs)
result = cairosvg.svg2png( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
**kwargs
)
if not isinstance(result, bytes):
raise Exception(
"Unexpected type returned by cairosvg.svg2png"
Expand Down
Loading

0 comments on commit b137179

Please sign in to comment.