Skip to content

Commit

Permalink
Fix mypy return-any warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronkollasch committed Aug 31, 2022
1 parent 922d356 commit 79e838b
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 14 deletions.
13 changes: 12 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ write_to_template = '''version = "{version}"
[tool.black]
line-length = 88
target-version = ['py38']
include = '^/(src|tests|benchmarks)/.*\.pyi?$'
include = '^/(src|tests|benchmarks|stubs)/.*\.pyi?$'
extend-exclude = '''
# A regex preceded with ^/ will apply only to files and directories
# in the root of the project.
Expand Down Expand Up @@ -43,3 +43,14 @@ markers = [
filterwarnings = [
"ignore:.*the imp module is deprecated.*:DeprecationWarning",
]

[tool.mypy]
ignore_missing_imports = true
warn_return_any = true
mypy_path = [
"src",
"stubs",
]
exclude = [
"photomanager/check_media_integrity/test_damage[.]py$",
]
4 changes: 4 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ flake8-black
coverage
twine
build
mypy
types-pillow
types-tqdm
types-xxhash
6 changes: 6 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ scripts =
where = src
exclude =
tests
stubs

[options.entry_points]
console_scripts =
Expand Down Expand Up @@ -107,10 +108,15 @@ deps =
isort
flake8
flake8-black
mypy
types-pillow
types-tqdm
types-xxhash
commands =
black --check --diff .
isort --check --diff .
flake8 --count src tests benchmarks
mypy src

[testenv:twine]
deps =
Expand Down
24 changes: 16 additions & 8 deletions src/photomanager/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from os import PathLike, cpu_count, makedirs, rename
from os.path import exists
from pathlib import Path
from typing import Optional, Type, TypeVar, Union
from typing import Optional, Type, TypedDict, TypeVar, Union, cast

import blake3
import orjson
Expand Down Expand Up @@ -53,7 +53,7 @@ def path_is_relative_to(
return path in subpath.parents


def tz_str_to_tzinfo(tz: str):
def tz_str_to_tzinfo(tz: str) -> Optional[tzinfo]:
"""
Convert a timezone string (e.g. -0400) to a tzinfo
If "local" or could not convert, return None
Expand All @@ -75,6 +75,14 @@ class DatabaseException(PhotoManagerBaseException):
DB = TypeVar("DB", bound="Database")


class DatabaseDict(TypedDict):
version: int
hash_algorithm: HashAlgorithm
timezone_default: str
photo_db: dict[str, list[PhotoFile]]
command_history: dict[str, str]


class Database:
VERSION = 3
"""
Expand All @@ -91,7 +99,7 @@ class Database:
)

def __init__(self):
self._db: dict = {
self._db: DatabaseDict = {
"version": self.VERSION,
"hash_algorithm": DEFAULT_HASH_ALGO,
"timezone_default": "local",
Expand Down Expand Up @@ -157,7 +165,7 @@ def sources(self) -> Generator[str, None, None]:
yield photo.src

@property
def db(self) -> dict:
def db(self) -> DatabaseDict:
"""Get the Database parameters as a dict."""
return self._db

Expand Down Expand Up @@ -185,7 +193,7 @@ def db(self, db: dict):
db["photo_db"][uid] = [PhotoFile.from_dict(d) for d in db["photo_db"][uid]]

db["version"] = self.VERSION
self._db = db
self._db = cast(DatabaseDict, db)

for uid, photos in self.photo_db.items():
for photo in photos:
Expand All @@ -201,7 +209,7 @@ def db(self, db: dict):
def from_dict(cls: Type[DB], db_dict: dict) -> DB:
"""Load a Database from a dictionary. Warning: can modify the dictionary."""
db = cls()
db.db = db_dict
db.db = cast(DatabaseDict, db_dict)
return db

@property
Expand Down Expand Up @@ -262,9 +270,9 @@ def from_file(cls: Type[DB], path: Union[str, PathLike], create_new=False) -> DB
with open(path, "rb") as f:
s = f.read()

db = orjson.loads(s)
db_dict = orjson.loads(s)
del s
db = cls.from_dict(db)
db = cls.from_dict(db_dict)
return db

def to_file(self, path: Union[str, PathLike], overwrite: bool = False) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/photomanager/hasher.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class HashAlgorithm(Enum):


class HashAlgorithmDefinition(TypedDict):
factory: Callable
factory: Callable[..., hashlib._Hash]
command: tuple[str, ...]
block_size: int

Expand Down
2 changes: 1 addition & 1 deletion src/photomanager/photofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,4 @@ def datetime_str_to_object(ts_str: str, tz_default: tzinfo = None) -> datetime:

def get_media_datetime(path: Union[str, PathLike]) -> str:
"""Gets the best known datetime string for a file"""
return ExifTool().get_best_datetime(path)
return ExifTool().get_best_datetime(path) or "no datetime found"
7 changes: 4 additions & 3 deletions src/photomanager/pyexiftool/pyexiftool.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@
d["EXIF:DateTimeOriginal"]))
"""

from __future__ import unicode_literals
from __future__ import annotations, unicode_literals

import logging
import subprocess
import warnings
from os import fsencode
from typing import Optional

import orjson

Expand Down Expand Up @@ -389,14 +390,14 @@ def get_tag(self, tag, filename):
else:
return None

def get_best_datetime_batch(self, filenames):
def get_best_datetime_batch(self, filenames) -> list[str]:
data = self.get_tags_batch(datetime_tags, filenames)
result = []
for d in data:
result.append(best_datetime(d))
return result

def get_best_datetime(self, filename):
def get_best_datetime(self, filename) -> Optional[str]:
if response := self.get_best_datetime_batch([filename]):
return response[0]
else:
Expand Down
1 change: 1 addition & 0 deletions stubs/blake3/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .blake3 import *
13 changes: 13 additions & 0 deletions stubs/blake3/blake3.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from hashlib import _Hash
from typing import Any, ClassVar

from _typeshed import ReadableBuffer, Self

class blake3(_Hash):
AUTO: ClassVar[int] = ...
block_size: ClassVar[int] = ...
digest_size: ClassVar[int] = ...
key_size: ClassVar[int] = ...
name: ClassVar[str] = ...
@classmethod
def __init__(cls, *args, **kwargs) -> None: ...

0 comments on commit 79e838b

Please sign in to comment.