diff options
author | Tim Brown <stimut@gmail.com> | 2020-10-28 09:30:48 +1000 |
---|---|---|
committer | Tim Brown <stimut@gmail.com> | 2020-10-28 09:30:48 +1000 |
commit | 08101e84488ec0ab4d2eae5dddbfc35328b7b0cb (patch) | |
tree | 5cfdf38aa7c83823ff79a132a327ee058586950b | |
parent | 37d7a195a9e47c8d6e3b603d90ad2130a7ce683e (diff) | |
download | qutebrowser-08101e84488ec0ab4d2eae5dddbfc35328b7b0cb.tar.gz qutebrowser-08101e84488ec0ab4d2eae5dddbfc35328b7b0cb.zip |
mypy: use from-import style
Update files in `api`, `commands`, `completion`, `components`, and
`etensions`.
See #5396
-rw-r--r-- | qutebrowser/api/cmdutils.py | 19 | ||||
-rw-r--r-- | qutebrowser/api/config.py | 6 | ||||
-rw-r--r-- | qutebrowser/api/hook.py | 8 | ||||
-rw-r--r-- | qutebrowser/commands/command.py | 15 | ||||
-rw-r--r-- | qutebrowser/commands/runners.py | 16 | ||||
-rw-r--r-- | qutebrowser/commands/userscripts.py | 10 | ||||
-rw-r--r-- | qutebrowser/completion/completionwidget.py | 6 | ||||
-rw-r--r-- | qutebrowser/completion/models/completionmodel.py | 5 | ||||
-rw-r--r-- | qutebrowser/completion/models/histcategory.py | 6 | ||||
-rw-r--r-- | qutebrowser/completion/models/listcategory.py | 4 | ||||
-rw-r--r-- | qutebrowser/completion/models/miscmodels.py | 10 | ||||
-rw-r--r-- | qutebrowser/completion/models/urlmodel.py | 10 | ||||
-rw-r--r-- | qutebrowser/completion/models/util.py | 4 | ||||
-rw-r--r-- | qutebrowser/components/adblock.py | 20 | ||||
-rw-r--r-- | qutebrowser/components/misccommands.py | 14 | ||||
-rw-r--r-- | qutebrowser/components/readlinecommands.py | 8 | ||||
-rw-r--r-- | qutebrowser/extensions/interceptors.py | 14 | ||||
-rw-r--r-- | qutebrowser/extensions/loader.py | 30 |
18 files changed, 100 insertions, 105 deletions
diff --git a/qutebrowser/api/cmdutils.py b/qutebrowser/api/cmdutils.py index 5d74991c1..7f0be1afd 100644 --- a/qutebrowser/api/cmdutils.py +++ b/qutebrowser/api/cmdutils.py @@ -44,13 +44,13 @@ Possible values: - A callable (``int``, ``float``, etc.): Gets called to validate/convert the value. - A python enum type: All members of the enum are possible values. -- A ``typing.Union`` of multiple types above: Any of these types are valid - values, e.g., ``typing.Union[str, int]``. +- A ``Union`` of multiple types above: Any of these types are valid + values, e.g., ``Union[str, int]``. """ import inspect -import typing +from typing import Any, Callable, Iterable from qutebrowser.utils import qtutils from qutebrowser.commands import command, cmdexc @@ -91,8 +91,7 @@ def check_overflow(arg: int, ctype: str) -> None: "representation.".format(ctype)) -def check_exclusive(flags: typing.Iterable[bool], - names: typing.Iterable[str]) -> None: +def check_exclusive(flags: Iterable[bool], names: Iterable[str]) -> None: """Check if only one flag is set with exclusive flags. Raise a CommandError if not. @@ -113,7 +112,7 @@ class register: # noqa: N801,N806 pylint: disable=invalid-name def __init__(self, *, instance: str = None, name: str = None, - **kwargs: typing.Any) -> None: + **kwargs: Any) -> None: """Save decorator arguments. Gets called on parse-time with the decorator arguments. @@ -128,7 +127,7 @@ class register: # noqa: N801,N806 pylint: disable=invalid-name # The arguments to pass to Command. self._kwargs = kwargs - def __call__(self, func: typing.Callable) -> typing.Callable: + def __call__(self, func: Callable) -> Callable: """Register the command before running the function. Gets called when a function should be decorated. @@ -175,7 +174,7 @@ class argument: # noqa: N801,N806 pylint: disable=invalid-name def foo(bar: str): ... - For ``typing.Union`` types, the given ``choices`` are only checked if other + For ``Union`` types, the given ``choices`` are only checked if other types (like ``int``) don't match. The following arguments are supported for ``@cmdutils.argument``: @@ -197,11 +196,11 @@ class argument: # noqa: N801,N806 pylint: disable=invalid-name trailing underscores stripped and underscores replaced by dashes. """ - def __init__(self, argname: str, **kwargs: typing.Any) -> None: + def __init__(self, argname: str, **kwargs: Any) -> None: self._argname = argname # The name of the argument to handle. self._kwargs = kwargs # Valid ArgInfo members. - def __call__(self, func: typing.Callable) -> typing.Callable: + def __call__(self, func: Callable) -> Callable: funcname = func.__name__ if self._argname not in inspect.signature(func).parameters: diff --git a/qutebrowser/api/config.py b/qutebrowser/api/config.py index 3b84a999c..fb363d858 100644 --- a/qutebrowser/api/config.py +++ b/qutebrowser/api/config.py @@ -19,7 +19,7 @@ """Access to the qutebrowser configuration.""" -import typing +from typing import cast, Any from PyQt5.QtCore import QUrl @@ -35,9 +35,9 @@ from qutebrowser.config import config #: This also supports setting configuration values:: #: #: config.val.content.javascript.enabled = False -val = typing.cast('config.ConfigContainer', None) +val = cast('config.ConfigContainer', None) -def get(name: str, url: QUrl = None) -> typing.Any: +def get(name: str, url: QUrl = None) -> Any: """Get a value from the config based on a string name.""" return config.instance.get(name, url) diff --git a/qutebrowser/api/hook.py b/qutebrowser/api/hook.py index 9bd14a8a1..4eadb2a99 100644 --- a/qutebrowser/api/hook.py +++ b/qutebrowser/api/hook.py @@ -22,13 +22,13 @@ """Hooks for extensions.""" import importlib -import typing +from typing import Callable from qutebrowser.extensions import loader -def _add_module_info(func: typing.Callable) -> loader.ModuleInfo: +def _add_module_info(func: Callable) -> loader.ModuleInfo: """Add module info to the given function.""" module = importlib.import_module(func.__module__) return loader.add_module_info(module) @@ -48,7 +48,7 @@ class init: message.info("Extension initialized.") """ - def __call__(self, func: typing.Callable) -> typing.Callable: + def __call__(self, func: Callable) -> Callable: info = _add_module_info(func) if info.init_hook is not None: raise ValueError("init hook is already registered!") @@ -86,7 +86,7 @@ class config_changed: def __init__(self, option_filter: str = None) -> None: self._filter = option_filter - def __call__(self, func: typing.Callable) -> typing.Callable: + def __call__(self, func: Callable) -> Callable: info = _add_module_info(func) info.config_changed_hooks.append((self._filter, func)) return func diff --git a/qutebrowser/commands/command.py b/qutebrowser/commands/command.py index 715bf4972..61b44d555 100644 --- a/qutebrowser/commands/command.py +++ b/qutebrowser/commands/command.py @@ -23,6 +23,7 @@ import inspect import collections import traceback import typing +from typing import Any, MutableMapping, MutableSequence, Tuple, Union import attr @@ -116,13 +117,11 @@ class Command: self.parser.add_argument('-h', '--help', action=argparser.HelpAction, default=argparser.SUPPRESS, nargs=0, help=argparser.SUPPRESS) - self.opt_args = collections.OrderedDict( - ) # type: typing.MutableMapping[str, typing.Tuple[str, str]] + self.opt_args: MutableMapping[str, Tuple[str, str]] = collections.OrderedDict() self.namespace = None self._count = None - self.pos_args = [ - ] # type: typing.MutableSequence[typing.Tuple[str, str]] - self.flags_with_args = [] # type: typing.MutableSequence[str] + self.pos_args: MutableSequence[Tuple[str, str]] = [] + self.flags_with_args: MutableSequence[str] = [] self._has_vararg = False # This is checked by future @cmdutils.argument calls so they fail @@ -412,7 +411,7 @@ class Command: # typing.get_origin was added in Python 3.8 origin = getattr(typ, '__origin__', None) - if origin is typing.Union: + if origin is Union: try: types = list(typing.get_args(typ)) # type: ignore[attr-defined] except AttributeError: @@ -494,8 +493,8 @@ class Command: Return: An (args, kwargs) tuple. """ - args = [] # type: typing.Any - kwargs = {} # type: typing.MutableMapping[str, typing.Any] + args: Any = [] + kwargs: MutableMapping[str, Any] = {} signature = inspect.signature(self.handler) for i, param in enumerate(signature.parameters.values()): diff --git a/qutebrowser/commands/runners.py b/qutebrowser/commands/runners.py index 76ae1d64f..c195a8be9 100644 --- a/qutebrowser/commands/runners.py +++ b/qutebrowser/commands/runners.py @@ -21,8 +21,8 @@ import traceback import re -import typing import contextlib +from typing import TYPE_CHECKING, Callable, Dict, Iterator, Mapping, MutableMapping import attr from PyQt5.QtCore import pyqtSlot, QUrl, QObject @@ -34,9 +34,9 @@ from qutebrowser.utils import message, objreg, qtutils, usertypes, utils from qutebrowser.misc import split, objects from qutebrowser.keyinput import macros, modeman -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from qutebrowser.mainwindow import tabbedbrowser -_ReplacementFunction = typing.Callable[['tabbedbrowser.TabbedBrowser'], str] +_ReplacementFunction = Callable[['tabbedbrowser.TabbedBrowser'], str] last_command = {} @@ -64,9 +64,9 @@ def _url(tabbed_browser): raise cmdutils.CommandError(msg) -def _init_variable_replacements() -> typing.Mapping[str, _ReplacementFunction]: +def _init_variable_replacements() -> Mapping[str, _ReplacementFunction]: """Return a dict from variable replacements to fns processing them.""" - replacements = { + replacements: Dict[str, _ReplacementFunction] = { 'url': lambda tb: _url(tb).toString( QUrl.FullyEncoded | QUrl.RemovePassword), 'url:pretty': lambda tb: _url(tb).toString( @@ -88,7 +88,7 @@ def _init_variable_replacements() -> typing.Mapping[str, _ReplacementFunction]: 'title': lambda tb: tb.widget.page_title(tb.widget.currentIndex()), 'clipboard': lambda _: utils.get_clipboard(), 'primary': lambda _: utils.get_clipboard(selection=True), - } # type: typing.Dict[str, _ReplacementFunction] + } for key in list(replacements): modified_key = '{' + key + '}' @@ -108,7 +108,7 @@ def replace_variables(win_id, arglist): """Utility function to replace variables like {url} in a list of args.""" tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) - values = {} # type: typing.MutableMapping[str, str] + values: MutableMapping[str, str] = {} args = [] def repl_cb(matchobj): @@ -332,7 +332,7 @@ class CommandRunner(AbstractCommandRunner): self._win_id = win_id @contextlib.contextmanager - def _handle_error(self, safely: bool) -> typing.Iterator[None]: + def _handle_error(self, safely: bool) -> Iterator[None]: """Show exceptions as errors if safely=True is given.""" try: yield diff --git a/qutebrowser/commands/userscripts.py b/qutebrowser/commands/userscripts.py index ba4cdfd93..ce25d7d28 100644 --- a/qutebrowser/commands/userscripts.py +++ b/qutebrowser/commands/userscripts.py @@ -22,7 +22,7 @@ import os import os.path import tempfile -import typing +from typing import cast, Any, MutableMapping, Tuple from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QSocketNotifier @@ -60,7 +60,7 @@ class _QtFIFOReader(QObject): fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK) # pylint: enable=no-member,useless-suppression self._fifo = os.fdopen(fd, 'r') - self._notifier = QSocketNotifier(typing.cast(sip.voidptr, fd), + self._notifier = QSocketNotifier(cast(sip.voidptr, fd), QSocketNotifier.Read, self) self._notifier.activated.connect( # type: ignore[attr-defined] self.read_line) @@ -117,10 +117,10 @@ class _BaseUserscriptRunner(QObject): self._cleaned_up = False self._filepath = None self._proc = None - self._env = {} # type: typing.MutableMapping[str, str] + self._env: MutableMapping[str, str] = {} self._text_stored = False self._html_stored = False - self._args = () # type: typing.Tuple[typing.Any, ...] + self._args: Tuple[Any, ...] = () self._kwargs = {} def store_text(self, text): @@ -426,7 +426,7 @@ def run_async(tab, cmd, *args, win_id, env, verbose=False, commandrunner = runners.CommandRunner(win_id, parent=tb) if utils.is_posix: - runner = _POSIXUserscriptRunner(tb) # type: _BaseUserscriptRunner + runner: _BaseUserscriptRunner = _POSIXUserscriptRunner(tb) elif utils.is_windows: # pragma: no cover runner = _WindowsUserscriptRunner(tb) else: # pragma: no cover diff --git a/qutebrowser/completion/completionwidget.py b/qutebrowser/completion/completionwidget.py index 50d5bdf62..4f51ecd4b 100644 --- a/qutebrowser/completion/completionwidget.py +++ b/qutebrowser/completion/completionwidget.py @@ -23,7 +23,7 @@ Defines a CompletionView which uses CompletionFiterModel and CompletionModel subclasses to provide completions. """ -import typing +from typing import TYPE_CHECKING, Optional from PyQt5.QtWidgets import QTreeView, QSizePolicy, QStyleFactory, QWidget from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QItemSelectionModel, QSize @@ -32,7 +32,7 @@ from qutebrowser.config import config, stylesheet from qutebrowser.completion import completiondelegate from qutebrowser.utils import utils, usertypes, debug, log from qutebrowser.api import cmdutils -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from qutebrowser.mainwindow.statusbar import command @@ -115,7 +115,7 @@ class CompletionView(QTreeView): win_id: int, parent: QWidget = None) -> None: super().__init__(parent) - self.pattern = None # type: typing.Optional[str] + self.pattern: Optional[str] = None self._win_id = win_id self._cmd = cmd self._active = False diff --git a/qutebrowser/completion/models/completionmodel.py b/qutebrowser/completion/models/completionmodel.py index 1bd2a808f..7d65d4439 100644 --- a/qutebrowser/completion/models/completionmodel.py +++ b/qutebrowser/completion/models/completionmodel.py @@ -19,7 +19,7 @@ """A model that proxies access to one or more completion categories.""" -import typing +from typing import MutableSequence from PyQt5.QtCore import Qt, QModelIndex, QAbstractItemModel @@ -43,8 +43,7 @@ class CompletionModel(QAbstractItemModel): def __init__(self, *, column_widths=(30, 70, 0), parent=None): super().__init__(parent) self.column_widths = column_widths - self._categories = [ - ] # type: typing.MutableSequence[QAbstractItemModel] + self._categories: MutableSequence[QAbstractItemModel] = [] def _cat_from_idx(self, index): """Return the category pointed to by the given index. diff --git a/qutebrowser/completion/models/histcategory.py b/qutebrowser/completion/models/histcategory.py index 464caa19e..e7ccd3505 100644 --- a/qutebrowser/completion/models/histcategory.py +++ b/qutebrowser/completion/models/histcategory.py @@ -19,7 +19,7 @@ """A completion category that queries the SQL history store.""" -import typing +from typing import Optional from PyQt5.QtSql import QSqlQueryModel from PyQt5.QtWidgets import QWidget @@ -40,12 +40,12 @@ class HistoryCategory(QSqlQueryModel): """Create a new History completion category.""" super().__init__(parent=parent) self.name = "History" - self._query = None # type: typing.Optional[sql.Query] + self._query: Optional[sql.Query] = None # advertise that this model filters by URL and title self.columns_to_filter = [0, 1] self.delete_func = delete_func - self._empty_prefix = None # type: typing.Optional[str] + self._empty_prefix: Optional[str] = None def _atime_expr(self): """If max_items is set, return an expression to limit the query.""" diff --git a/qutebrowser/completion/models/listcategory.py b/qutebrowser/completion/models/listcategory.py index 6995071ed..f0cc21da0 100644 --- a/qutebrowser/completion/models/listcategory.py +++ b/qutebrowser/completion/models/listcategory.py @@ -20,7 +20,7 @@ """Completion category that uses a list of tuples as a data source.""" import re -import typing +from typing import Iterable, Tuple from PyQt5.QtCore import Qt, QSortFilterProxyModel, QRegExp from PyQt5.QtGui import QStandardItem, QStandardItemModel @@ -36,7 +36,7 @@ class ListCategory(QSortFilterProxyModel): def __init__(self, name: str, - items: typing.Iterable[typing.Tuple[str, ...]], + items: Iterable[Tuple[str, ...]], sort: bool = True, delete_func: util.DeleteFuncType = None, parent: QWidget = None): diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index 9cf2d5fd6..925f95bbb 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -20,7 +20,7 @@ """Functions that return miscellaneous completion models.""" import datetime -import typing +from typing import List, Sequence, Tuple from qutebrowser.config import config, configdata from qutebrowser.utils import objreg, log, utils @@ -53,7 +53,7 @@ def helptopic(*, info): def quickmark(*, info=None): """A CompletionModel filled with all quickmarks.""" - def delete(data: typing.Sequence[str]) -> None: + def delete(data: Sequence[str]) -> None: """Delete a quickmark from the completion menu.""" name = data[0] quickmark_manager = objreg.get('quickmark-manager') @@ -71,7 +71,7 @@ def quickmark(*, info=None): def bookmark(*, info=None): """A CompletionModel filled with all bookmarks.""" - def delete(data: typing.Sequence[str]) -> None: + def delete(data: Sequence[str]) -> None: """Delete a bookmark from the completion menu.""" urlstr = data[0] log.completion.debug('Deleting bookmark {}'.format(urlstr)) @@ -121,7 +121,7 @@ def _buffer(*, win_id_filter=lambda _win_id: True, add_win_id=True): tabs_are_windows = config.val.tabs.tabs_are_windows # list storing all single-tabbed windows when tabs_are_windows - windows = [] # type: typing.List[typing.Tuple[str, str, str]] + windows: List[Tuple[str, str, str]] = [] for win_id in objreg.window_registry: if not win_id_filter(win_id): @@ -131,7 +131,7 @@ def _buffer(*, win_id_filter=lambda _win_id: True, add_win_id=True): window=win_id) if tabbed_browser.is_shutting_down: continue - tabs = [] # type: typing.List[typing.Tuple[str, str, str]] + tabs: List[Tuple[str, str, str]] = [] for idx in range(tabbed_browser.widget.count()): tab = tabbed_browser.widget.widget(idx) tab_str = ("{}/{}".format(win_id, idx + 1) if add_win_id diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index ff83a598a..b245cf5c4 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -19,9 +19,9 @@ """Function to return the url completion model for the `open` command.""" -import typing +from typing import TYPE_CHECKING, Dict, Sequence -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from PyQt5.QtCore import QAbstractItemModel from qutebrowser.completion.models import (completionmodel, listcategory, @@ -41,14 +41,14 @@ def _delete_history(data): history.web_history.delete_url(urlstr) -def _delete_bookmark(data: typing.Sequence[str]) -> None: +def _delete_bookmark(data: Sequence[str]) -> None: urlstr = data[_URLCOL] log.completion.debug('Deleting bookmark {}'.format(urlstr)) bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.delete(urlstr) -def _delete_quickmark(data: typing.Sequence[str]) -> None: +def _delete_quickmark(data: Sequence[str]) -> None: name = data[_TEXTCOL] quickmark_manager = objreg.get('quickmark-manager') log.completion.debug('Deleting quickmark {}'.format(name)) @@ -77,7 +77,7 @@ def url(*, info): if k != 'DEFAULT'] # pylint: enable=bad-config-option categories = config.val.completion.open_categories - models = {} # type: typing.Dict[str, QAbstractItemModel] + models: Dict[str, 'QAbstractItemModel'] = {} if searchengines and 'searchengines' in categories: models['searchengines'] = listcategory.ListCategory( diff --git a/qutebrowser/completion/models/util.py b/qutebrowser/completion/models/util.py index a0dda334a..7f4f6d19d 100644 --- a/qutebrowser/completion/models/util.py +++ b/qutebrowser/completion/models/util.py @@ -19,13 +19,13 @@ """Utility functions for completion models.""" -import typing +from typing import Callable, Sequence from qutebrowser.utils import usertypes from qutebrowser.misc import objects -DeleteFuncType = typing.Callable[[typing.Sequence[str]], None] +DeleteFuncType = Callable[[Sequence[str]], None] def get_cmd_completions(info, include_hidden, include_aliases, prefix=''): diff --git a/qutebrowser/components/adblock.py b/qutebrowser/components/adblock.py index b34711fdd..f9b0a583b 100644 --- a/qutebrowser/components/adblock.py +++ b/qutebrowser/components/adblock.py @@ -24,8 +24,8 @@ import functools import posixpath import zipfile import logging -import typing import pathlib +from typing import cast, IO, List, Set from PyQt5.QtCore import QUrl @@ -34,7 +34,7 @@ from qutebrowser.api import (cmdutils, hook, config, message, downloads, logger = logging.getLogger('network') -_host_blocker = typing.cast('HostBlocker', None) +_host_blocker = cast('HostBlocker', None) def _guess_zip_filename(zf: zipfile.ZipFile) -> str: @@ -49,7 +49,7 @@ def _guess_zip_filename(zf: zipfile.ZipFile) -> str: raise FileNotFoundError("No hosts file found in zip") -def get_fileobj(byte_io: typing.IO[bytes]) -> typing.IO[bytes]: +def get_fileobj(byte_io: IO[bytes]) -> IO[bytes]: """Get a usable file object to read the hosts file from.""" byte_io.seek(0) # rewind downloaded file if zipfile.is_zipfile(byte_io): @@ -75,7 +75,7 @@ class _FakeDownload(downloads.TempDownload): """A download stub to use on_download_finished with local files.""" def __init__(self, # pylint: disable=super-init-not-called - fileobj: typing.IO[bytes]) -> None: + fileobj: IO[bytes]) -> None: self.fileobj = fileobj self.successful = True @@ -97,9 +97,9 @@ class HostBlocker: def __init__(self, *, data_dir: pathlib.Path, config_dir: pathlib.Path, has_basedir: bool = False) -> None: self._has_basedir = has_basedir - self._blocked_hosts = set() # type: typing.Set[str] - self._config_blocked_hosts = set() # type: typing.Set[str] - self._in_progress = [] # type: typing.List[downloads.TempDownload] + self._blocked_hosts: Set[str] = set() + self._config_blocked_hosts: Set[str] = set() + self._in_progress: List[downloads.TempDownload] = [] self._done_count = 0 self._local_hosts_file = str(data_dir / 'blocked-hosts') @@ -132,7 +132,7 @@ class HostBlocker: .format(info.request_url.host())) info.block() - def _read_hosts_line(self, raw_line: bytes) -> typing.Set[str]: + def _read_hosts_line(self, raw_line: bytes) -> Set[str]: """Read hosts from the given line. Args: @@ -170,7 +170,7 @@ class HostBlocker: return filtered_hosts - def _read_hosts_file(self, filename: str, target: typing.Set[str]) -> bool: + def _read_hosts_file(self, filename: str, target: Set[str]) -> bool: """Read hosts from the given filename. Args: @@ -246,7 +246,7 @@ class HostBlocker: self._in_progress.append(download) self._on_download_finished(download) - def _merge_file(self, byte_io: typing.IO[bytes]) -> None: + def _merge_file(self, byte_io: IO[bytes]) -> None: """Read and merge host files. Args: diff --git a/qutebrowser/components/misccommands.py b/qutebrowser/components/misccommands.py index ff9a21070..19ad126c1 100644 --- a/qutebrowser/components/misccommands.py +++ b/qutebrowser/components/misccommands.py @@ -23,7 +23,7 @@ import os import signal import functools import logging -import typing +from typing import Optional try: import hunter @@ -41,7 +41,7 @@ from qutebrowser.completion.models import miscmodels @cmdutils.register(name='reload') @cmdutils.argument('tab', value=cmdutils.Value.count_tab) -def reloadpage(tab: typing.Optional[apitypes.Tab], +def reloadpage(tab: Optional[apitypes.Tab], force: bool = False) -> None: """Reload the current/[count]th tab. @@ -55,7 +55,7 @@ def reloadpage(tab: typing.Optional[apitypes.Tab], @cmdutils.register() @cmdutils.argument('tab', value=cmdutils.Value.count_tab) -def stop(tab: typing.Optional[apitypes.Tab]) -> None: +def stop(tab: Optional[apitypes.Tab]) -> None: """Stop loading in the current/[count]th tab. Args: @@ -97,7 +97,7 @@ def _print_pdf(tab: apitypes.Tab, filename: str) -> None: @cmdutils.register(name='print') @cmdutils.argument('tab', value=cmdutils.Value.count_tab) @cmdutils.argument('pdf', flag='f', metavar='file') -def printpage(tab: typing.Optional[apitypes.Tab], +def printpage(tab: Optional[apitypes.Tab], preview: bool = False, *, pdf: str = None) -> None: """Print the current/[count]th tab. @@ -163,7 +163,7 @@ def insert_text(tab: apitypes.Tab, text: str) -> None: Args: text: The text to insert. """ - def _insert_text_cb(elem: typing.Optional[apitypes.WebElement]) -> None: + def _insert_text_cb(elem: Optional[apitypes.WebElement]) -> None: if elem is None: message.error("No element focused!") return @@ -195,7 +195,7 @@ def click_element(tab: apitypes.Tab, filter_: str, value: str, *, target: How to open the clicked element (normal/tab/tab-bg/window). force_event: Force generating a fake click event. """ - def single_cb(elem: typing.Optional[apitypes.WebElement]) -> None: + def single_cb(elem: Optional[apitypes.WebElement]) -> None: """Click a single element.""" if elem is None: message.error("No element found with id {}!".format(value)) @@ -236,7 +236,7 @@ def debug_webaction(tab: apitypes.Tab, action: str, count: int = 1) -> None: @cmdutils.register() @cmdutils.argument('tab', value=cmdutils.Value.count_tab) -def tab_mute(tab: typing.Optional[apitypes.Tab]) -> None: +def tab_mute(tab: Optional[apitypes.Tab]) -> None: """Mute/Unmute the current/[count]th tab. Args: diff --git a/qutebrowser/components/readlinecommands.py b/qutebrowser/components/readlinecommands.py index 076bb9055..ea8f12edf 100644 --- a/qutebrowser/components/readlinecommands.py +++ b/qutebrowser/components/readlinecommands.py @@ -19,7 +19,7 @@ """Bridge to provide readline-like shortcuts for QLineEdits.""" -import typing +from typing import Iterable, Optional, MutableMapping from PyQt5.QtWidgets import QApplication, QLineEdit @@ -35,9 +35,9 @@ class _ReadlineBridge: """ def __init__(self) -> None: - self._deleted = {} # type: typing.MutableMapping[QLineEdit, str] + self._deleted: MutableMapping[QLineEdit, str] = {} - def _widget(self) -> typing.Optional[QLineEdit]: + def _widget(self) -> Optional[QLineEdit]: """Get the currently active QLineEdit.""" w = QApplication.instance().focusWidget() if isinstance(w, QLineEdit): @@ -86,7 +86,7 @@ class _ReadlineBridge: def kill_line(self) -> None: self._dispatch('end', mark=True, delete=True) - def _rubout(self, delim: typing.Iterable[str]) -> None: + def _rubout(self, delim: Iterable[str]) -> None: """Delete backwards using the characters in delim as boundaries.""" widget = self._widget() if widget is None: diff --git a/qutebrowser/extensions/interceptors.py b/qutebrowser/extensions/interceptors.py index 6c5756016..fddeaabc9 100644 --- a/qutebrowser/extensions/interceptors.py +++ b/qutebrowser/extensions/interceptors.py @@ -19,8 +19,8 @@ """Infrastructure for intercepting requests.""" -import typing import enum +from typing import Callable, List, Optional import attr @@ -76,15 +76,15 @@ class Request: """A request which can be intercepted/blocked.""" #: The URL of the page being shown. - first_party_url = attr.ib() # type: typing.Optional[QUrl] + first_party_url: Optional[QUrl] = attr.ib() #: The URL of the file being requested. - request_url = attr.ib() # type: QUrl + request_url: QUrl = attr.ib() - is_blocked = attr.ib(False) # type: bool + is_blocked: bool = attr.ib(False) #: The resource type of the request. None if not supported on this backend. - resource_type = attr.ib(None) # type: typing.Optional[ResourceType] + resource_type: Optional[ResourceType] = attr.ib(None) def block(self) -> None: """Block this request.""" @@ -107,10 +107,10 @@ class Request: #: Type annotation for an interceptor function. -InterceptorType = typing.Callable[[Request], None] +InterceptorType = Callable[[Request], None] -_interceptors = [] # type: typing.List[InterceptorType] +_interceptors: List[InterceptorType] = [] def register(interceptor: InterceptorType) -> None: diff --git a/qutebrowser/extensions/loader.py b/qutebrowser/extensions/loader.py index f4649401f..bbaa81be9 100644 --- a/qutebrowser/extensions/loader.py +++ b/qutebrowser/extensions/loader.py @@ -21,10 +21,10 @@ import pkgutil import types -import typing import sys import pathlib import importlib +from typing import TYPE_CHECKING, Callable, Iterator, List, Optional, Set, Tuple import attr @@ -35,7 +35,7 @@ from qutebrowser.config import config from qutebrowser.utils import log, standarddir from qutebrowser.misc import objects -if typing.TYPE_CHECKING: +if TYPE_CHECKING: import argparse @@ -48,9 +48,9 @@ class InitContext: """Context an extension gets in its init hook.""" - data_dir = attr.ib() # type: pathlib.Path - config_dir = attr.ib() # type: pathlib.Path - args = attr.ib() # type: argparse.Namespace + data_dir: pathlib.Path = attr.ib() + config_dir: pathlib.Path = attr.ib() + args: 'argparse.Namespace' = attr.ib() @attr.s @@ -61,13 +61,11 @@ class ModuleInfo: This gets used by qutebrowser.api.hook. """ - _ConfigChangedHooksType = typing.List[typing.Tuple[typing.Optional[str], - typing.Callable]] + _ConfigChangedHooksType = List[Tuple[Optional[str], Callable]] - skip_hooks = attr.ib(False) # type: bool - init_hook = attr.ib(None) # type: typing.Optional[typing.Callable] - config_changed_hooks = attr.ib( - attr.Factory(list)) # type: _ConfigChangedHooksType + skip_hooks: bool = attr.ib(False) + init_hook: Optional[Callable] = attr.ib(None) + config_changed_hooks: _ConfigChangedHooksType = attr.ib(attr.Factory(list)) @attr.s @@ -75,7 +73,7 @@ class ExtensionInfo: """Information about a qutebrowser extension.""" - name = attr.ib() # type: str + name: str = attr.ib() def add_module_info(module: types.ModuleType) -> ModuleInfo: @@ -92,7 +90,7 @@ def load_components(*, skip_hooks: bool = False) -> None: _load_component(info, skip_hooks=skip_hooks) -def walk_components() -> typing.Iterator[ExtensionInfo]: +def walk_components() -> Iterator[ExtensionInfo]: """Yield ExtensionInfo objects for all modules.""" if hasattr(sys, 'frozen'): yield from _walk_pyinstaller() @@ -104,7 +102,7 @@ def _on_walk_error(name: str) -> None: raise ImportError("Failed to import {}".format(name)) -def _walk_normal() -> typing.Iterator[ExtensionInfo]: +def _walk_normal() -> Iterator[ExtensionInfo]: """Walk extensions when not using PyInstaller.""" for _finder, name, ispkg in pkgutil.walk_packages( # Only packages have a __path__ attribute, @@ -117,7 +115,7 @@ def _walk_normal() -> typing.Iterator[ExtensionInfo]: yield ExtensionInfo(name=name) -def _walk_pyinstaller() -> typing.Iterator[ExtensionInfo]: +def _walk_pyinstaller() -> Iterator[ExtensionInfo]: """Walk extensions when using PyInstaller. See https://github.com/pyinstaller/pyinstaller/issues/1905 @@ -125,7 +123,7 @@ def _walk_pyinstaller() -> typing.Iterator[ExtensionInfo]: Inspired by: https://github.com/webcomics/dosage/blob/master/dosagelib/loader.py """ - toc = set() # type: typing.Set[str] + toc: Set[str] = set() for importer in pkgutil.iter_importers('qutebrowser'): if hasattr(importer, 'toc'): toc |= importer.toc |