diff options
author | Florian Bruhin <me@the-compiler.org> | 2022-03-29 21:29:10 +0200 |
---|---|---|
committer | Florian Bruhin <me@the-compiler.org> | 2022-03-29 21:29:49 +0200 |
commit | 562f358050ef1c40dda441809561330c9127a928 (patch) | |
tree | 4852641f7780f1d580da135af203a27701f0d913 | |
parent | b6800acf488b6b5a3eb8ea789e77fcf8a59e420e (diff) | |
download | qutebrowser-562f358050ef1c40dda441809561330c9127a928.tar.gz qutebrowser-562f358050ef1c40dda441809561330c9127a928.zip |
mypy: Fix typing around importlib.resources
mypy was correct here: _path doesn't always return a pathlib.Path, it's why we need to handle that in _glob().
-rw-r--r-- | qutebrowser/utils/resources.py | 23 |
1 files changed, 14 insertions, 9 deletions
diff --git a/qutebrowser/utils/resources.py b/qutebrowser/utils/resources.py index f561d6747..f9b59661e 100644 --- a/qutebrowser/utils/resources.py +++ b/qutebrowser/utils/resources.py @@ -24,19 +24,28 @@ import sys import contextlib import posixpath import pathlib -from typing import Iterator, Iterable +from typing import Iterator, Iterable, Union # We cannot use the stdlib version on 3.7-3.8 because we need the files() API. if sys.version_info >= (3, 9): import importlib.resources as importlib_resources + from importlib.abc import Traversable else: # pragma: no cover import importlib_resources + from importlib_resources.abc import Traversable import qutebrowser _cache = {} -def _path(filename: str) -> pathlib.Path: + +# Unfortunately, we can't tell mypy about this also possibly being a +# zipfile.Path because we set "python_version = 3.6" in .mypy.ini, but the +# zipfile stubs (correctly) only declare zipfile.Path with Python 3.8... +_ResourceType = Union[Traversable, pathlib.Path] + + +def _path(filename: str) -> _ResourceType: """Get a pathlib.Path object for a resource.""" assert not posixpath.isabs(filename), filename assert os.path.pardir not in filename.split(posixpath.sep), filename @@ -64,7 +73,7 @@ def _keyerror_workaround() -> Iterator[None]: def _glob( - resource_path: pathlib.Path, + resource_path: _ResourceType, subdir: str, ext: str, ) -> Iterable[str]: @@ -79,12 +88,8 @@ def _glob( if isinstance(resource_path, pathlib.Path): for full_path in glob_path.glob(f'*{ext}'): # . is contained in ext yield full_path.relative_to(resource_path).as_posix() - else: # zipfile.Path or importlib_resources compat object - # Unfortunately, we can't tell mypy about resource_path being of type - # Union[pathlib.Path, zipfile.Path] because we set "python_version = 3.6" in - # .mypy.ini, but the zipfile stubs (correctly) only declare zipfile.Path with - # Python 3.8... - assert glob_path.is_dir(), glob_path # type: ignore[unreachable] + else: # zipfile.Path or importlib_resources.abc.Traversable + assert glob_path.is_dir(), glob_path for subpath in glob_path.iterdir(): if subpath.name.endswith(ext): yield posixpath.join(subdir, subpath.name) |