summaryrefslogtreecommitdiff
path: root/qutebrowser/utils
diff options
context:
space:
mode:
authorFlorian Bruhin <me@the-compiler.org>2021-05-19 13:15:09 +0200
committerFlorian Bruhin <me@the-compiler.org>2021-05-19 13:15:09 +0200
commitc01b47f27b46a8568096977363b38b01d138749c (patch)
treed0b47c3e9bebc757638f57a17a20e2cbc0332d15 /qutebrowser/utils
parent06e49efd3d9f21058893a0c3751aa05caaf0e2f8 (diff)
downloadqutebrowser-c01b47f27b46a8568096977363b38b01d138749c.tar.gz
qutebrowser-c01b47f27b46a8568096977363b38b01d138749c.zip
mypy: Set disallow_any_generics
See #6100
Diffstat (limited to 'qutebrowser/utils')
-rw-r--r--qutebrowser/utils/debug.py34
-rw-r--r--qutebrowser/utils/docutils.py4
-rw-r--r--qutebrowser/utils/objreg.py3
-rw-r--r--qutebrowser/utils/qtutils.py13
-rw-r--r--qutebrowser/utils/urlmatch.py9
-rw-r--r--qutebrowser/utils/utils.py9
6 files changed, 46 insertions, 26 deletions
diff --git a/qutebrowser/utils/debug.py b/qutebrowser/utils/debug.py
index 54fcd5aa9..7d069909a 100644
--- a/qutebrowser/utils/debug.py
+++ b/qutebrowser/utils/debug.py
@@ -35,7 +35,7 @@ from qutebrowser.misc import objects
from qutebrowser.qt import sip
-def log_events(klass: Type) -> Type:
+def log_events(klass: Type[QObject]) -> Type[QObject]:
"""Class decorator to log Qt events."""
old_event = klass.event
@@ -46,7 +46,7 @@ def log_events(klass: Type) -> Type:
qenum_key(QEvent, e.type())))
return old_event(self, e)
- klass.event = new_event
+ klass.event = new_event # type: ignore[assignment]
return klass
@@ -96,10 +96,13 @@ def log_signals(obj: QObject) -> QObject:
return obj
-def qenum_key(base: Type,
- value: Union[int, sip.simplewrapper],
+_EnumValueType = Union[sip.simplewrapper, int]
+
+
+def qenum_key(base: Type[_EnumValueType],
+ value: _EnumValueType,
add_base: bool = False,
- klass: Type = None) -> str:
+ klass: Type[_EnumValueType] = None) -> str:
"""Convert a Qt Enum value to its key as a string.
Args:
@@ -119,8 +122,9 @@ def qenum_key(base: Type,
raise TypeError("Can't guess enum class of an int!")
try:
- idx = base.staticMetaObject.indexOfEnumerator(klass.__name__)
- meta_enum = base.staticMetaObject.enumerator(idx)
+ meta_obj = base.staticMetaObject # type: ignore[union-attr]
+ idx = meta_obj.indexOfEnumerator(klass.__name__)
+ meta_enum = meta_obj.enumerator(idx)
ret = meta_enum.valueToKey(int(value)) # type: ignore[arg-type]
except AttributeError:
ret = None
@@ -139,10 +143,10 @@ def qenum_key(base: Type,
return ret
-def qflags_key(base: Type,
- value: Union[int, sip.simplewrapper],
+def qflags_key(base: Type[_EnumValueType],
+ value: _EnumValueType,
add_base: bool = False,
- klass: Type = None) -> str:
+ klass: Type[_EnumValueType] = None) -> str:
"""Convert a Qt QFlags value to its keys as string.
Note: Passing a combined value (such as Qt.AlignCenter) will get the names
@@ -220,7 +224,7 @@ def signal_name(sig: pyqtBoundSignal) -> str:
return m.group('name')
-def format_args(args: Sequence = None, kwargs: Mapping = None) -> str:
+def format_args(args: Sequence[Any] = None, kwargs: Mapping[str, Any] = None) -> str:
"""Format a list of arguments/kwargs to a function-call like string."""
if args is not None:
arglist = [utils.compact_text(repr(arg), 200) for arg in args]
@@ -245,9 +249,9 @@ def dbg_signal(sig: pyqtBoundSignal, args: Any) -> str:
return '{}({})'.format(signal_name(sig), format_args(args))
-def format_call(func: Callable,
- args: Sequence = None,
- kwargs: Mapping = None,
+def format_call(func: Callable[..., Any],
+ args: Sequence[Any] = None,
+ kwargs: Mapping[str, Any] = None,
full: bool = True) -> str:
"""Get a string representation of a function calls with the given args.
@@ -302,7 +306,7 @@ class log_time: # noqa: N801,N806 pylint: disable=invalid-name
self._logger.debug("{} took {} seconds.".format(
self._action.capitalize(), delta))
- def __call__(self, func: Callable) -> Callable:
+ def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(func)
def wrapped(*args: Any, **kwargs: Any) -> Any:
"""Call the original function."""
diff --git a/qutebrowser/utils/docutils.py b/qutebrowser/utils/docutils.py
index 202fcba95..89e799c89 100644
--- a/qutebrowser/utils/docutils.py
+++ b/qutebrowser/utils/docutils.py
@@ -25,7 +25,7 @@ import inspect
import os.path
import collections
import enum
-from typing import Callable, MutableMapping, Optional, List, Union
+from typing import Any, Callable, MutableMapping, Optional, List, Union
import qutebrowser
from qutebrowser.utils import log, utils
@@ -88,7 +88,7 @@ class DocstringParser:
arg_inside = enum.auto()
misc = enum.auto()
- def __init__(self, func: Callable) -> None:
+ def __init__(self, func: Callable[..., Any]) -> None:
"""Constructor.
Args:
diff --git a/qutebrowser/utils/objreg.py b/qutebrowser/utils/objreg.py
index 99d8a0936..0819a5d0a 100644
--- a/qutebrowser/utils/objreg.py
+++ b/qutebrowser/utils/objreg.py
@@ -55,7 +55,8 @@ class CommandOnlyError(Exception):
_IndexType = Union[str, int]
-class ObjectRegistry(collections.UserDict):
+# UserDict is only generic in Python 3.9+
+class ObjectRegistry(collections.UserDict): # type: ignore[type-arg]
"""A registry of long-living objects in qutebrowser.
diff --git a/qutebrowser/utils/qtutils.py b/qutebrowser/utils/qtutils.py
index 01234a42b..ff8983c50 100644
--- a/qutebrowser/utils/qtutils.py
+++ b/qutebrowser/utils/qtutils.py
@@ -31,7 +31,8 @@ Module attributes:
import io
import operator
import contextlib
-from typing import TYPE_CHECKING, BinaryIO, IO, Iterator, Optional, Union, Tuple, cast
+from typing import (Any, AnyStr, TYPE_CHECKING, BinaryIO, IO, Iterator,
+ Optional, Union, Tuple, cast)
from PyQt5.QtCore import (qVersion, QEventLoop, QDataStream, QByteArray,
QIODevice, QFileDevice, QSaveFile, QT_VERSION_STR,
@@ -227,7 +228,7 @@ def savefile_open(
filename: str,
binary: bool = False,
encoding: str = 'utf-8'
-) -> Iterator[IO]:
+) -> Iterator[IO[AnyStr]]:
"""Context manager to easily use a QSaveFile."""
f = QSaveFile(filename)
cancelled = False
@@ -239,7 +240,7 @@ def savefile_open(
dev = cast(BinaryIO, PyQIODevice(f))
if binary:
- new_f: IO = dev
+ new_f: IO[Any] = dev # FIXME:mypy Why doesn't AnyStr work?
else:
new_f = io.TextIOWrapper(dev, encoding=encoding)
@@ -298,7 +299,11 @@ class PyQIODevice(io.BufferedIOBase):
if not self.writable():
raise OSError("Trying to write to unwritable file!")
- def open(self, mode: QIODevice.OpenMode) -> contextlib.closing:
+ # contextlib.closing is only generic in Python 3.9+
+ def open(
+ self,
+ mode: QIODevice.OpenMode,
+ ) -> contextlib.closing: # type: ignore[type-arg]
"""Open the underlying device and ensure opening succeeded.
Raises OSError if opening failed.
diff --git a/qutebrowser/utils/urlmatch.py b/qutebrowser/utils/urlmatch.py
index 8dfd6d273..f14c2083d 100644
--- a/qutebrowser/utils/urlmatch.py
+++ b/qutebrowser/utils/urlmatch.py
@@ -104,7 +104,14 @@ class UrlPattern:
self._init_path(parsed)
self._init_port(parsed)
- def _to_tuple(self) -> Tuple:
+ def _to_tuple(self) -> Tuple[
+ bool, # _match_all
+ bool, # _match_subdomains
+ Optional[str], # _scheme
+ Optional[str], # host
+ Optional[str], # _path
+ Optional[int], # _port
+ ]:
"""Get a pattern with information used for __eq__/__hash__."""
return (self._match_all, self._match_subdomains, self._scheme,
self.host, self._path, self._port)
diff --git a/qutebrowser/utils/utils.py b/qutebrowser/utils/utils.py
index 56ebe45c4..fb0165de2 100644
--- a/qutebrowser/utils/utils.py
+++ b/qutebrowser/utils/utils.py
@@ -341,7 +341,7 @@ class prevent_exceptions: # noqa: N801,N806 pylint: disable=invalid-name
self._retval = retval
self._predicate = predicate
- def __call__(self, func: Callable) -> Callable:
+ def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
"""Called when a function should be decorated.
Args:
@@ -447,7 +447,7 @@ def qualname(obj: Any) -> str:
_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException]]]
-def raises(exc: _ExceptionType, func: Callable, *args: Any) -> bool:
+def raises(exc: _ExceptionType, func: Callable[..., Any], *args: Any) -> bool:
"""Check if a function raises a given exception.
Args:
@@ -725,7 +725,10 @@ def yaml_dump(data: Any, f: IO[str] = None) -> Optional[str]:
return yaml_data.decode('utf-8')
-def chunk(elems: Sequence, n: int) -> Iterator[Sequence]:
+_T = TypeVar('_T')
+
+
+def chunk(elems: Sequence[_T], n: int) -> Iterator[Sequence[_T]]:
"""Yield successive n-sized chunks from elems.
If elems % n != 0, the last chunk will be smaller.