diff options
author | Tim Brown <stimut@gmail.com> | 2020-10-28 21:35:24 +1000 |
---|---|---|
committer | Tim Brown <stimut@gmail.com> | 2020-10-28 21:35:24 +1000 |
commit | 8ae8883c4bb6c1a3e9925a38e530cbe980898d5c (patch) | |
tree | c4779f809181301f28ee066cba0622a87171cd98 | |
parent | 37d7a195a9e47c8d6e3b603d90ad2130a7ce683e (diff) | |
download | qutebrowser-8ae8883c4bb6c1a3e9925a38e530cbe980898d5c.tar.gz qutebrowser-8ae8883c4bb6c1a3e9925a38e530cbe980898d5c.zip |
mypy: use from-import style for typing
Update files in `keyinput`, `mainwindow`, and `misc`.
See #5396
25 files changed, 155 insertions, 175 deletions
diff --git a/qutebrowser/keyinput/basekeyparser.py b/qutebrowser/keyinput/basekeyparser.py index dea85aede..23b77cba1 100644 --- a/qutebrowser/keyinput/basekeyparser.py +++ b/qutebrowser/keyinput/basekeyparser.py @@ -21,7 +21,7 @@ import string import types -import typing +from typing import Mapping, MutableMapping, Optional, Sequence import attr from PyQt5.QtCore import pyqtSignal, QObject, Qt @@ -37,9 +37,9 @@ class MatchResult: """The result of matching a keybinding.""" - match_type = attr.ib() # type: QKeySequence.SequenceMatch - command = attr.ib() # type: typing.Optional[str] - sequence = attr.ib() # type: keyutils.KeySequence + match_type: QKeySequence.SequenceMatch = attr.ib() + command: Optional[str] = attr.ib() + sequence: keyutils.KeySequence = attr.ib() def __attrs_post_init__(self) -> None: if self.match_type == QKeySequence.ExactMatch: @@ -75,9 +75,8 @@ class BindingTrie: __slots__ = 'children', 'command' def __init__(self) -> None: - self.children = { - } # type: typing.MutableMapping[keyutils.KeyInfo, BindingTrie] - self.command = None # type: typing.Optional[str] + self.children: MutableMapping[keyutils.KeyInfo, BindingTrie] = {} + self.command: Optional[str] = None def __setitem__(self, sequence: keyutils.KeySequence, command: str) -> None: @@ -99,8 +98,7 @@ class BindingTrie: def __str__(self) -> str: return '\n'.join(self.string_lines(blank=True)) - def string_lines(self, indent: int = 0, - blank: bool = False) -> typing.Sequence[str]: + def string_lines(self, indent: int = 0, blank: bool = False) -> Sequence[str]: """Get a list of strings for a pretty-printed version of this trie.""" lines = [] if self.command is not None: @@ -114,7 +112,7 @@ class BindingTrie: return lines - def update(self, mapping: typing.Mapping) -> None: + def update(self, mapping: Mapping) -> None: """Add data from the given mapping to the trie.""" for key in mapping: self[key] = mapping[key] diff --git a/qutebrowser/keyinput/eventfilter.py b/qutebrowser/keyinput/eventfilter.py index 6ef0dd201..d77c8702d 100644 --- a/qutebrowser/keyinput/eventfilter.py +++ b/qutebrowser/keyinput/eventfilter.py @@ -19,7 +19,7 @@ """Global Qt event filter which dispatches key events.""" -import typing +from typing import cast from PyQt5.QtCore import pyqtSlot, QObject, QEvent from PyQt5.QtGui import QKeyEvent, QWindow @@ -102,7 +102,7 @@ class EventFilter(QObject): handler = self._handlers[typ] try: - return handler(typing.cast(QKeyEvent, event)) + return handler(cast(QKeyEvent, event)) except: # If there is an exception in here and we leave the eventfilter # activated, we'll get an infinite loop and a stack overflow. diff --git a/qutebrowser/keyinput/keyutils.py b/qutebrowser/keyinput/keyutils.py index b95f4a55d..aa5457c6d 100644 --- a/qutebrowser/keyinput/keyutils.py +++ b/qutebrowser/keyinput/keyutils.py @@ -32,7 +32,7 @@ handle what we actually think we do. """ import itertools -import typing +from typing import cast, overload, Iterable, Iterator, List, Mapping, Optional, Union import attr from PyQt5.QtCore import Qt, QEvent @@ -53,10 +53,10 @@ _MODIFIER_MAP = { _NIL_KEY = Qt.Key(0) -_ModifierType = typing.Union[Qt.KeyboardModifier, Qt.KeyboardModifiers] +_ModifierType = Union[Qt.KeyboardModifier, Qt.KeyboardModifiers] -def _build_special_names() -> typing.Mapping[Qt.Key, str]: +def _build_special_names() -> Mapping[Qt.Key, str]: """Build _SPECIAL_NAMES dict from the special_names_str mapping below. The reason we don't do this directly is that certain Qt versions don't have @@ -231,8 +231,7 @@ def _remap_unicode(key: Qt.Key, text: str) -> Qt.Key: return key -def _check_valid_utf8(s: str, - data: typing.Union[Qt.Key, _ModifierType]) -> None: +def _check_valid_utf8(s: str, data: Union[Qt.Key, _ModifierType]) -> None: """Make sure the given string is valid UTF-8. Makes sure there are no chars where Qt did fall back to weird UTF-16 @@ -288,7 +287,7 @@ class KeyParseError(Exception): """Raised by _parse_single_key/parse_keystring on parse errors.""" - def __init__(self, keystr: typing.Optional[str], error: str) -> None: + def __init__(self, keystr: Optional[str], error: str) -> None: if keystr is None: msg = "Could not parse keystring: {}".format(error) else: @@ -296,7 +295,7 @@ class KeyParseError(Exception): super().__init__(msg) -def _parse_keystring(keystr: str) -> typing.Iterator[str]: +def _parse_keystring(keystr: str) -> Iterator[str]: key = '' special = False for c in keystr: @@ -363,8 +362,8 @@ class KeyInfo: modifiers: A Qt::KeyboardModifiers enum value. """ - key = attr.ib() # type: Qt.Key - modifiers = attr.ib() # type: _ModifierType + key: Qt.Key = attr.ib() + modifiers: _ModifierType = attr.ib() @classmethod def from_event(cls, e: QKeyEvent) -> 'KeyInfo': @@ -377,7 +376,7 @@ class KeyInfo: modifiers = e.modifiers() _assert_plain_key(key) _assert_plain_modifier(modifiers) - return cls(key, typing.cast(Qt.KeyboardModifier, modifiers)) + return cls(key, cast(Qt.KeyboardModifier, modifiers)) def __hash__(self) -> int: """Convert KeyInfo to int before hashing. @@ -473,7 +472,7 @@ class KeySequence: _MAX_LEN = 4 def __init__(self, *keys: int) -> None: - self._sequences = [] # type: typing.List[QKeySequence] + self._sequences: List[QKeySequence] = [] for sub in utils.chunk(keys, self._MAX_LEN): args = [self._convert_key(key) for key in sub] sequence = QKeySequence(*args) @@ -493,7 +492,7 @@ class KeySequence: parts.append(str(info)) return ''.join(parts) - def __iter__(self) -> typing.Iterator[KeyInfo]: + def __iter__(self) -> Iterator[KeyInfo]: """Iterate over KeyInfo objects.""" for key_and_modifiers in self._iter_keys(): key = Qt.Key(int(key_and_modifiers) & ~Qt.KeyboardModifierMask) @@ -535,17 +534,15 @@ class KeySequence: def __bool__(self) -> bool: return bool(self._sequences) - @typing.overload + @overload def __getitem__(self, item: int) -> KeyInfo: ... - @typing.overload + @overload def __getitem__(self, item: slice) -> 'KeySequence': ... - def __getitem__( - self, item: typing.Union[int, slice] - ) -> typing.Union[KeyInfo, 'KeySequence']: + def __getitem__(self, item: Union[int, slice]) -> Union[KeyInfo, 'KeySequence']: if isinstance(item, slice): keys = list(self._iter_keys()) return self.__class__(*keys[item]) @@ -553,9 +550,8 @@ class KeySequence: infos = list(self) return infos[item] - def _iter_keys(self) -> typing.Iterator[int]: - sequences = typing.cast(typing.Iterable[typing.Iterable[int]], - self._sequences) + def _iter_keys(self) -> Iterator[int]: + sequences = cast(Iterable[Iterable[int]], self._sequences) return itertools.chain.from_iterable(sequences) def _validate(self, keystr: str = None) -> None: @@ -664,7 +660,7 @@ class KeySequence: def with_mappings( self, - mappings: typing.Mapping['KeySequence', 'KeySequence'] + mappings: Mapping['KeySequence', 'KeySequence'] ) -> 'KeySequence': """Get a new KeySequence with the given mappings applied.""" keys = [] diff --git a/qutebrowser/keyinput/macros.py b/qutebrowser/keyinput/macros.py index 6e48e5a3f..ee8883070 100644 --- a/qutebrowser/keyinput/macros.py +++ b/qutebrowser/keyinput/macros.py @@ -20,7 +20,7 @@ """Keyboard macro system.""" -import typing +from typing import cast, Dict, List, Optional, Tuple from qutebrowser.commands import runners from qutebrowser.api import cmdutils @@ -28,9 +28,9 @@ from qutebrowser.keyinput import modeman from qutebrowser.utils import message, objreg, usertypes -_CommandType = typing.Tuple[str, int] # command, type +_CommandType = Tuple[str, int] # command, type -macro_recorder = typing.cast('MacroRecorder', None) +macro_recorder = cast('MacroRecorder', None) class MacroRecorder: @@ -47,10 +47,10 @@ class MacroRecorder: """ def __init__(self) -> None: - self._macros = {} # type: typing.Dict[str, typing.List[_CommandType]] - self._recording_macro = None # type: typing.Optional[str] - self._macro_count = {} # type: typing.Dict[int, int] - self._last_register = None # type: typing.Optional[str] + self._macros: Dict[str, List[_CommandType]] = {} + self._recording_macro: Optional[str] = None + self._macro_count: Dict[int, int] = {} + self._last_register: Optional[str] = None @cmdutils.register(instance='macro-recorder', name='record-macro') @cmdutils.argument('win_id', value=cmdutils.Value.win_id) diff --git a/qutebrowser/keyinput/modeman.py b/qutebrowser/keyinput/modeman.py index e49aa891d..27e4be34e 100644 --- a/qutebrowser/keyinput/modeman.py +++ b/qutebrowser/keyinput/modeman.py @@ -19,7 +19,6 @@ """Mode manager (per window) which handles the current keyboard mode.""" -import typing import functools from typing import Mapping, Callable, MutableMapping, Union, Set, cast @@ -265,7 +264,7 @@ class ModeManager(QObject): self.mode = usertypes.KeyMode.normal self._releaseevents_to_pass = set() # type: Set[KeyEvent] # Set after __init__ - self.hintmanager = typing.cast(hints.HintManager, None) + self.hintmanager = cast(hints.HintManager, None) def __repr__(self) -> str: return utils.get_repr(self, mode=self.mode) diff --git a/qutebrowser/keyinput/modeparsers.py b/qutebrowser/keyinput/modeparsers.py index dd8ee37f6..48f3594a5 100644 --- a/qutebrowser/keyinput/modeparsers.py +++ b/qutebrowser/keyinput/modeparsers.py @@ -23,9 +23,9 @@ Module attributes: STARTCHARS: Possible chars for starting a commandline input. """ -import typing import traceback import enum +from typing import TYPE_CHECKING, Sequence from PyQt5.QtCore import pyqtSlot, Qt, QObject from PyQt5.QtGui import QKeySequence, QKeyEvent @@ -35,7 +35,7 @@ from qutebrowser.commands import cmdexc from qutebrowser.config import config from qutebrowser.keyinput import basekeyparser, keyutils, macros from qutebrowser.utils import usertypes, log, message, objreg, utils -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from qutebrowser.commands import runners @@ -232,7 +232,7 @@ class HintKeyParser(basekeyparser.BaseKeyParser): return match - def update_bindings(self, strings: typing.Sequence[str], + def update_bindings(self, strings: Sequence[str], preserve_filter: bool = False) -> None: """Update bindings when the hint strings changed. diff --git a/qutebrowser/mainwindow/mainwindow.py b/qutebrowser/mainwindow/mainwindow.py index 34d99c312..b8228545a 100644 --- a/qutebrowser/mainwindow/mainwindow.py +++ b/qutebrowser/mainwindow/mainwindow.py @@ -23,7 +23,7 @@ import binascii import base64 import itertools import functools -import typing +from typing import List, MutableSequence, Optional, Tuple, cast from PyQt5.QtCore import (pyqtBoundSignal, pyqtSlot, QRect, QPoint, QTimer, Qt, QCoreApplication, QEventLoop, QByteArray) @@ -118,7 +118,7 @@ def get_target_window(): return None -_OverlayInfoType = typing.Tuple[QWidget, pyqtBoundSignal, bool, str] +_OverlayInfoType = Tuple[QWidget, pyqtBoundSignal, bool, str] class MainWindow(QWidget): @@ -187,8 +187,8 @@ class MainWindow(QWidget): def __init__(self, *, private: bool, - geometry: typing.Optional[QByteArray] = None, - parent: typing.Optional[QWidget] = None) -> None: + geometry: Optional[QByteArray] = None, + parent: Optional[QWidget] = None) -> None: """Create a new main window. Args: @@ -205,7 +205,7 @@ class MainWindow(QWidget): self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_TranslucentBackground) self.palette().setColor(QPalette.Window, Qt.transparent) - self._overlays = [] # type: typing.MutableSequence[_OverlayInfoType] + self._overlays: MutableSequence[_OverlayInfoType] = [] self.win_id = next(win_id_gen) self.registry = objreg.ObjectRegistry() objreg.window_registry[self.win_id] = self @@ -226,9 +226,8 @@ class MainWindow(QWidget): self.is_private = config.val.content.private_browsing or private - self.tabbed_browser = tabbedbrowser.TabbedBrowser( - win_id=self.win_id, private=self.is_private, parent=self - ) # type: tabbedbrowser.TabbedBrowser + self.tabbed_browser: tabbedbrowser.TabbedBrowser = tabbedbrowser.TabbedBrowser( + win_id=self.win_id, private=self.is_private, parent=self) objreg.register('tabbed-browser', self.tabbed_browser, scope='window', window=self.win_id) self._init_command_dispatcher() @@ -413,7 +412,7 @@ class MainWindow(QWidget): self._vbox.removeWidget(self.tabbed_browser.widget) self._vbox.removeWidget(self._downloadview) self._vbox.removeWidget(self.status) - widgets = [self.tabbed_browser.widget] # type: typing.List[QWidget] + widgets: List[QWidget] = [self.tabbed_browser.widget] downloads_position = config.val.downloads.position if downloads_position == 'top': @@ -558,11 +557,11 @@ class MainWindow(QWidget): def _set_decoration(self, hidden): """Set the visibility of the window decoration via Qt.""" - window_flags = Qt.Window # type: int + window_flags: int = Qt.Window refresh_window = self.isVisible() if hidden: window_flags |= Qt.CustomizeWindowHint | Qt.NoDropShadowWindowHint - self.setWindowFlags(typing.cast(Qt.WindowFlags, window_flags)) + self.setWindowFlags(cast(Qt.WindowFlags, window_flags)) if refresh_window: self.show() diff --git a/qutebrowser/mainwindow/messageview.py b/qutebrowser/mainwindow/messageview.py index 1f6295d89..9c4b63084 100644 --- a/qutebrowser/mainwindow/messageview.py +++ b/qutebrowser/mainwindow/messageview.py @@ -19,7 +19,7 @@ """Showing messages above the statusbar.""" -import typing +from typing import MutableSequence from PyQt5.QtCore import pyqtSlot, pyqtSignal, QTimer, Qt from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy @@ -76,7 +76,7 @@ class MessageView(QWidget): def __init__(self, parent=None): super().__init__(parent) - self._messages = [] # type: typing.MutableSequence[Message] + self._messages: MutableSequence[Message] = [] self._vbox = QVBoxLayout(self) self._vbox.setContentsMargins(0, 0, 0, 0) self._vbox.setSpacing(0) diff --git a/qutebrowser/mainwindow/prompt.py b/qutebrowser/mainwindow/prompt.py index a929d6428..7836e5883 100644 --- a/qutebrowser/mainwindow/prompt.py +++ b/qutebrowser/mainwindow/prompt.py @@ -23,7 +23,7 @@ import os.path import html import collections import functools -import typing +from typing import Deque, MutableSequence, Optional, cast import attr from PyQt5.QtCore import (pyqtSlot, pyqtSignal, Qt, QTimer, QDir, QModelIndex, @@ -40,7 +40,7 @@ from qutebrowser.api import cmdutils from qutebrowser.utils import urlmatch -prompt_queue = typing.cast('PromptQueue', None) +prompt_queue = cast('PromptQueue', None) @attr.s @@ -102,9 +102,8 @@ class PromptQueue(QObject): super().__init__(parent) self._question = None self._shutting_down = False - self._loops = [] # type: typing.MutableSequence[qtutils.EventLoop] - self._queue = collections.deque( - ) # type: typing.Deque[usertypes.Question] + self._loops: MutableSequence[qtutils.EventLoop] = [] + self._queue: Deque[usertypes.Question] = collections.deque() message.global_bridge.mode_left.connect(self._on_mode_left) def __repr__(self): @@ -196,8 +195,8 @@ class PromptQueue(QObject): question.completed.connect(loop.quit) question.completed.connect(loop.deleteLater) log.prompt.debug("Starting loop.exec_() for {}".format(question)) - flags = typing.cast(QEventLoop.ProcessEventsFlags, - QEventLoop.ExcludeSocketNotifiers) + flags = cast(QEventLoop.ProcessEventsFlags, + QEventLoop.ExcludeSocketNotifiers) loop.exec_(flags) log.prompt.debug("Ending loop.exec_() for {}".format(question)) @@ -289,7 +288,7 @@ class PromptContainer(QWidget): self._layout = QVBoxLayout(self) self._layout.setContentsMargins(10, 10, 10, 10) self._win_id = win_id - self._prompt = None # type: typing.Optional[_BasePrompt] + self._prompt: Optional[_BasePrompt] = None self.setObjectName('PromptContainer') self.setAttribute(Qt.WA_StyledBackground, True) @@ -794,8 +793,8 @@ class DownloadFilenamePrompt(FilenamePrompt): def download_open(self, cmdline, pdfjs): if pdfjs: - target = downloads.PDFJSDownloadTarget( - ) # type: downloads._DownloadTarget + target: downloads._DownloadTarget = ( # pylint: disable=protected-access + downloads.PDFJSDownloadTarget()) else: target = downloads.OpenFileDownloadTarget(cmdline) diff --git a/qutebrowser/mainwindow/tabbedbrowser.py b/qutebrowser/mainwindow/tabbedbrowser.py index 57a9ae018..2523cdaeb 100644 --- a/qutebrowser/mainwindow/tabbedbrowser.py +++ b/qutebrowser/mainwindow/tabbedbrowser.py @@ -22,8 +22,9 @@ import collections import functools import weakref -import typing import datetime +from typing import ( + Any, Deque, List, Mapping, MutableMapping, MutableSequence, Optional, Tuple) import attr from PyQt5.QtWidgets import QSizePolicy, QWidget, QApplication @@ -68,12 +69,10 @@ class TabDeque: size = config.val.tabs.focus_stack_size if size < 0: size = None - self._stack = collections.deque( - maxlen=size - ) # type: typing.Deque[weakref.ReferenceType[QWidget]] + self._stack: Deque[weakref.ReferenceType[QWidget]] = collections.deque( + maxlen=size) # Items that have been removed from the primary stack. - self._stack_deleted = [ - ] # type: typing.List[weakref.ReferenceType[QWidget]] + self._stack_deleted: List[weakref.ReferenceType[QWidget]] = [] self._ignore_next = False self._keep_deleted_next = False @@ -94,7 +93,7 @@ class TabDeque: Throws IndexError on failure. """ - tab = None # type: typing.Optional[QWidget] + tab: Optional[QWidget] = None while tab is None or tab.pending_removal or tab is cur_tab: tab = self._stack.pop()() self._stack_deleted.append(weakref.ref(cur_tab)) @@ -106,7 +105,7 @@ class TabDeque: Throws IndexError on failure. """ - tab = None # type: typing.Optional[QWidget] + tab: Optional[QWidget] = None while tab is None or tab.pending_removal or tab is cur_tab: tab = self._stack_deleted.pop()() # On next tab-switch, current tab will be added to stack as normal. @@ -224,18 +223,15 @@ class TabbedBrowser(QWidget): # This init is never used, it is immediately thrown away in the next # line. - self.undo_stack = ( - collections.deque() - ) # type: typing.MutableSequence[typing.MutableSequence[_UndoEntry]] + self.undo_stack: MutableSequence[MutableSequence[_UndoEntry]] = ( + collections.deque()) self._update_stack_size() self._filter = signalfilter.SignalFilter(win_id, self) self._now_focused = None self.search_text = None - self.search_options = {} # type: typing.Mapping[str, typing.Any] - self._local_marks = { - } # type: typing.MutableMapping[QUrl, typing.MutableMapping[str, int]] - self._global_marks = { - } # type: typing.MutableMapping[str, typing.Tuple[int, QUrl]] + self.search_options: Mapping[str, Any] = {} + self._local_marks: MutableMapping[QUrl, MutableMapping[str, int]] = {} + self._global_marks: MutableMapping[str, Tuple[int, QUrl]] = {} self.default_window_icon = self.widget.window().windowIcon() self.is_private = private self.tab_deque = TabDeque() diff --git a/qutebrowser/mainwindow/tabwidget.py b/qutebrowser/mainwindow/tabwidget.py index f5a417398..b40c59bd5 100644 --- a/qutebrowser/mainwindow/tabwidget.py +++ b/qutebrowser/mainwindow/tabwidget.py @@ -19,9 +19,9 @@ """The tab widget used for TabbedBrowser from browser.py.""" -import typing import functools import contextlib +from typing import Optional, cast import attr from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Qt, QSize, QRect, QPoint, @@ -339,8 +339,7 @@ class TabWidget(QTabWidget): def setTabIcon(self, idx: int, icon: QIcon) -> None: """Always show tab icons for pinned tabs in some circumstances.""" - tab = typing.cast(typing.Optional[browsertab.AbstractTab], - self.widget(idx)) + tab = cast(Optional[browsertab.AbstractTab], self.widget(idx)) if (icon.isNull() and config.cache['tabs.favicons.show'] != 'never' and config.cache['tabs.pinned.shrink'] and diff --git a/qutebrowser/mainwindow/windowundo.py b/qutebrowser/mainwindow/windowundo.py index 4a4ea5d66..af7b2766a 100644 --- a/qutebrowser/mainwindow/windowundo.py +++ b/qutebrowser/mainwindow/windowundo.py @@ -20,7 +20,7 @@ """Code for :undo --window.""" import collections -import typing +from typing import MutableSequence, cast import attr from PyQt5.QtCore import QObject @@ -30,7 +30,7 @@ from qutebrowser.config import config from qutebrowser.mainwindow import mainwindow -instance = typing.cast('WindowUndoManager', None) +instance = cast('WindowUndoManager', None) @attr.s @@ -48,9 +48,7 @@ class WindowUndoManager(QObject): def __init__(self, parent=None): super().__init__(parent) - self._undos = ( - collections.deque() - ) # type: typing.MutableSequence[_WindowUndoEntry] + self._undos: MutableSequence[_WindowUndoEntry] = collections.deque() QApplication.instance().window_closing.connect(self._on_window_closing) config.instance.changed.connect(self._on_config_changed) diff --git a/qutebrowser/misc/backendproblem.py b/qutebrowser/misc/backendproblem.py index 089e3191f..f9c210f15 100644 --- a/qutebrowser/misc/backendproblem.py +++ b/qutebrowser/misc/backendproblem.py @@ -25,8 +25,8 @@ import functools import html import enum import shutil -import typing import argparse +from typing import Any, List, Sequence, Tuple import attr from PyQt5.QtCore import Qt @@ -55,15 +55,13 @@ class _Button: """A button passed to BackendProblemDialog.""" - text = attr.ib() # type: str - setting = attr.ib() # type: str - value = attr.ib() # type: typing.Any - default = attr.ib(default=False) # type: bool + text: str = attr.ib() + setting: str = attr.ib() + value: Any = attr.ib() + default: bool = attr.ib(default=False) -def _other_backend( - backend: usertypes.Backend -) -> typing.Tuple[usertypes.Backend, str]: +def _other_backend(backend: usertypes.Backend) -> Tuple[usertypes.Backend, str]: """Get the other backend enum/setting for a given backend.""" other_backend = { usertypes.Backend.QtWebKit: usertypes.Backend.QtWebEngine, @@ -103,7 +101,7 @@ class _Dialog(QDialog): def __init__(self, *, because: str, text: str, backend: usertypes.Backend, - buttons: typing.Sequence[_Button] = None, + buttons: Sequence[_Button] = None, parent: QWidget = None) -> None: super().__init__(parent) vbox = QVBoxLayout(self) @@ -157,10 +155,10 @@ class _BackendImports: """Whether backend modules could be imported.""" - webkit_available = attr.ib(default=None) # type: bool - webengine_available = attr.ib(default=None) # type: bool - webkit_error = attr.ib(default=None) # type: str - webengine_error = attr.ib(default=None) # type: str + webkit_available: bool = attr.ib(default=None) + webengine_available: bool = attr.ib(default=None) + webkit_error: str = attr.ib(default=None) + webengine_error: str = attr.ib(default=None) class _BackendProblemChecker: @@ -181,7 +179,7 @@ class _BackendProblemChecker: self._save_manager = save_manager self._no_err_windows = no_err_windows - def _show_dialog(self, *args: typing.Any, **kwargs: typing.Any) -> None: + def _show_dialog(self, *args: Any, **kwargs: Any) -> None: """Show a dialog for a backend problem.""" if self._no_err_windows: text = _error_text(*args, **kwargs) @@ -255,7 +253,7 @@ class _BackendProblemChecker: raise utils.Unreachable - def _xwayland_options(self) -> typing.Tuple[str, typing.List[_Button]]: + def _xwayland_options(self) -> Tuple[str, List[_Button]]: """Get buttons/text for a possible XWayland solution.""" buttons = [] text = "<p>You can work around this in one of the following ways:</p>" diff --git a/qutebrowser/misc/cmdhistory.py b/qutebrowser/misc/cmdhistory.py index 810bbd1f9..1403ee56d 100644 --- a/qutebrowser/misc/cmdhistory.py +++ b/qutebrowser/misc/cmdhistory.py @@ -19,7 +19,7 @@ """Command history for the status bar.""" -import typing +from typing import MutableSequence from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject @@ -60,7 +60,7 @@ class History(QObject): super().__init__(parent) self._tmphist = None if history is None: - self.history = [] # type: typing.MutableSequence[str] + self.history: MutableSequence[str] = [] else: self.history = history @@ -82,9 +82,9 @@ class History(QObject): """ log.misc.debug("Preset text: '{}'".format(text)) if text: - items = [ + items: MutableSequence[str] = [ e for e in self.history - if e.startswith(text)] # type: typing.MutableSequence[str] + if e.startswith(text)] else: items = self.history if not items: diff --git a/qutebrowser/misc/crashsignal.py b/qutebrowser/misc/crashsignal.py index 3f80db769..65e584bc9 100644 --- a/qutebrowser/misc/crashsignal.py +++ b/qutebrowser/misc/crashsignal.py @@ -29,7 +29,7 @@ import argparse import functools import threading import faulthandler -import typing +from typing import TYPE_CHECKING, Optional, MutableMapping, cast try: # WORKAROUND for segfaults when using pdb in pytest for some reason... import readline # pylint: disable=unused-import @@ -45,7 +45,7 @@ from qutebrowser.api import cmdutils from qutebrowser.misc import earlyinit, crashdialog, ipc, objects from qutebrowser.utils import usertypes, standarddir, log, objreg, debug, utils from qutebrowser.qt import sip -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from qutebrowser.misc import quitter @@ -59,7 +59,7 @@ class ExceptionInfo: objects = attr.ib() -crash_handler = typing.cast('CrashHandler', None) +crash_handler = cast('CrashHandler', None) class CrashHandler(QObject): @@ -337,10 +337,9 @@ class SignalHandler(QObject): self._quitter = quitter self._notifier = None self._timer = usertypes.Timer(self, 'python_hacks') - self._orig_handlers = { - } # type: typing.MutableMapping[int, signal._HANDLER] + self._orig_handlers: MutableMapping[int, 'signal._HANDLER'] = {} self._activated = False - self._orig_wakeup_fd = None # type: typing.Optional[int] + self._orig_wakeup_fd: Optional[int] = None def activate(self): """Set up signal handlers. @@ -363,7 +362,7 @@ class SignalHandler(QObject): for fd in [read_fd, write_fd]: flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) - self._notifier = QSocketNotifier(typing.cast(sip.voidptr, read_fd), + self._notifier = QSocketNotifier(cast(sip.voidptr, read_fd), QSocketNotifier.Read, self) self._notifier.activated.connect( # type: ignore[attr-defined] diff --git a/qutebrowser/misc/debugcachestats.py b/qutebrowser/misc/debugcachestats.py index 417e4505a..227f9d668 100644 --- a/qutebrowser/misc/debugcachestats.py +++ b/qutebrowser/misc/debugcachestats.py @@ -23,17 +23,17 @@ Because many modules depend on this command, this needs to have as few dependencies as possible to avoid cyclic dependencies. """ -import typing +from typing import Any, Callable, List, Optional, Tuple, TypeVar # The second element of each tuple should be a lru_cache wrapped function -_CACHE_FUNCTIONS = [] # type: typing.List[typing.Tuple[str, typing.Any]] +_CACHE_FUNCTIONS: List[Tuple[str, Any]] = [] -_T = typing.TypeVar('_T', bound=typing.Callable) +_T = TypeVar('_T', bound=Callable) -def register(name: typing.Optional[str] = None) -> typing.Callable[[_T], _T]: +def register(name: Optional[str] = None) -> Callable[[_T], _T]: """Register a lru_cache wrapped function for debug_cache_stats.""" def wrapper(fn: _T) -> _T: _CACHE_FUNCTIONS.append((fn.__name__ if name is None else name, fn)) diff --git a/qutebrowser/misc/httpclient.py b/qutebrowser/misc/httpclient.py index 176a70e07..b9502ca43 100644 --- a/qutebrowser/misc/httpclient.py +++ b/qutebrowser/misc/httpclient.py @@ -19,9 +19,9 @@ """An HTTP client based on QNetworkAccessManager.""" -import typing import functools import urllib.parse +from typing import MutableMapping from PyQt5.QtCore import pyqtSignal, QObject, QTimer from PyQt5.QtNetwork import (QNetworkAccessManager, QNetworkRequest, @@ -66,7 +66,7 @@ class HTTPClient(QObject): def __init__(self, parent=None): super().__init__(parent) self._nam = QNetworkAccessManager(self) - self._timers = {} # type: typing.MutableMapping[QNetworkReply, QTimer] + self._timers: MutableMapping[QNetworkReply, QTimer] = {} def post(self, url, data=None): """Create a new POST request. diff --git a/qutebrowser/misc/lineparser.py b/qutebrowser/misc/lineparser.py index 749c5dff1..d3e5a2db0 100644 --- a/qutebrowser/misc/lineparser.py +++ b/qutebrowser/misc/lineparser.py @@ -22,7 +22,7 @@ import os import os.path import contextlib -import typing +from typing import Sequence from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject @@ -150,7 +150,7 @@ class LineParser(BaseLineParser): """ super().__init__(configdir, fname, binary=binary, parent=parent) if not os.path.isfile(self._configfile): - self.data = [] # type: typing.Sequence[str] + self.data: Sequence[str] = [] else: log.init.debug("Reading {}".format(self._configfile)) self._read() diff --git a/qutebrowser/misc/miscwidgets.py b/qutebrowser/misc/miscwidgets.py index 2310a1926..a38607390 100644 --- a/qutebrowser/misc/miscwidgets.py +++ b/qutebrowser/misc/miscwidgets.py @@ -19,7 +19,7 @@ """Misc. widgets used at different places.""" -import typing +from typing import Optional from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QSize, QTimer from PyQt5.QtWidgets import (QLineEdit, QWidget, QHBoxLayout, QLabel, @@ -239,8 +239,8 @@ class WrapperLayout(QLayout): def __init__(self, parent=None): super().__init__(parent) - self._widget = None # type: typing.Optional[QWidget] - self._container = None # type: typing.Optional[QWidget] + self._widget: Optional[QWidget] = None + self._container: Optional[QWidget] = None def addItem(self, _widget): raise utils.Unreachable @@ -390,10 +390,10 @@ class InspectorSplitter(QSplitter): self.addWidget(main_webview) self.setFocusProxy(main_webview) self.splitterMoved.connect(self._on_splitter_moved) - self._main_idx = None # type: typing.Optional[int] - self._inspector_idx = None # type: typing.Optional[int] - self._position = None # type: typing.Optional[inspector.Position] - self._preferred_size = None # type: typing.Optional[int] + self._main_idx: Optional[int] = None + self._inspector_idx: Optional[int] = None + self._position: Optional[inspector.Position] = None + self._preferred_size: Optional[int] = None def cycle_focus(self): """Cycle keyboard focus between the main/inspector widget.""" diff --git a/qutebrowser/misc/objects.py b/qutebrowser/misc/objects.py index 28a1830d5..c2e20e9ad 100644 --- a/qutebrowser/misc/objects.py +++ b/qutebrowser/misc/objects.py @@ -22,10 +22,10 @@ # NOTE: We need to be careful with imports here, as this is imported from # earlyinit. -import typing import argparse +from typing import TYPE_CHECKING, Any, Dict, Set, Union, cast -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from qutebrowser.utils import usertypes from qutebrowser.commands import command @@ -38,11 +38,11 @@ class NoBackend: def name(self) -> str: raise AssertionError("No backend set!") - def __eq__(self, other: typing.Any) -> bool: + def __eq__(self, other: Any) -> bool: raise AssertionError("No backend set!") -backend = NoBackend() # type: typing.Union[usertypes.Backend, NoBackend] -commands = {} # type: typing.Dict[str, command.Command] -debug_flags = set() # type: typing.Set[str] -args = typing.cast(argparse.Namespace, None) +backend: Union['usertypes.Backend', NoBackend] = NoBackend() +commands: Dict[str, 'command.Command'] = {} +debug_flags: Set[str] = set() +args = cast(argparse.Namespace, None) diff --git a/qutebrowser/misc/quitter.py b/qutebrowser/misc/quitter.py index c7f0c8072..86342d57b 100644 --- a/qutebrowser/misc/quitter.py +++ b/qutebrowser/misc/quitter.py @@ -25,11 +25,11 @@ import sys import json import atexit import shutil -import typing import argparse import tokenize import functools import subprocess +from typing import Iterable, Mapping, MutableSequence, Sequence, cast from PyQt5.QtCore import QObject, pyqtSignal, QTimer from PyQt5.QtWidgets import QApplication @@ -46,7 +46,7 @@ from qutebrowser.mainwindow import prompt from qutebrowser.completion.models import miscmodels -instance = typing.cast('Quitter', None) +instance = cast('Quitter', None) class Quitter(QObject): @@ -97,10 +97,10 @@ class Quitter(QObject): compile(f.read(), fn, 'exec') def _get_restart_args( - self, pages: typing.Iterable[str] = (), + self, pages: Iterable[str] = (), session: str = None, - override_args: typing.Mapping[str, str] = None - ) -> typing.Sequence[str]: + override_args: Mapping[str, str] = None + ) -> Sequence[str]: """Get args to relaunch qutebrowser. Args: @@ -120,7 +120,7 @@ class Quitter(QObject): args = [sys.executable, '-m', 'qutebrowser'] # Add all open pages so they get reopened. - page_args = [] # type: typing.MutableSequence[str] + page_args: MutableSequence[str] = [] for win in pages: page_args.extend(win) page_args.append('') @@ -157,9 +157,9 @@ class Quitter(QObject): return args - def restart(self, pages: typing.Sequence[str] = (), + def restart(self, pages: Sequence[str] = (), session: str = None, - override_args: typing.Mapping[str, str] = None) -> bool: + override_args: Mapping[str, str] = None) -> bool: """Inner logic to restart qutebrowser. The "better" way to restart is to pass a session (_restart usually) as diff --git a/qutebrowser/misc/savemanager.py b/qutebrowser/misc/savemanager.py index daa484934..c7a20adbb 100644 --- a/qutebrowser/misc/savemanager.py +++ b/qutebrowser/misc/savemanager.py @@ -21,7 +21,7 @@ import os.path import collections -import typing +from typing import MutableMapping from PyQt5.QtCore import pyqtSlot, QObject, QTimer @@ -112,8 +112,7 @@ class SaveManager(QObject): def __init__(self, parent=None): super().__init__(parent) - self.saveables = collections.OrderedDict( - ) # type: typing.MutableMapping[str, Saveable] + self.saveables: MutableMapping[str, Saveable] = collections.OrderedDict() self._save_timer = usertypes.Timer(self, name='save-timer') self._save_timer.timeout.connect(self.autosave) self._set_autosave_interval() diff --git a/qutebrowser/misc/sessions.py b/qutebrowser/misc/sessions.py index 0ebb415ac..eecc1964e 100644 --- a/qutebrowser/misc/sessions.py +++ b/qutebrowser/misc/sessions.py @@ -23,9 +23,9 @@ import os import os.path import itertools import urllib -import typing import glob import shutil +from typing import Any, Iterable, MutableMapping, MutableSequence, Optional, Union, cast from PyQt5.QtCore import Qt, QUrl, QObject, QPoint, QTimer, QDateTime from PyQt5.QtWidgets import QApplication @@ -40,7 +40,7 @@ from qutebrowser.mainwindow import mainwindow from qutebrowser.qt import sip -_JsonType = typing.MutableMapping[str, typing.Any] +_JsonType = MutableMapping[str, Any] class Sentinel: @@ -49,9 +49,9 @@ class Sentinel: default = Sentinel() -session_manager = typing.cast('SessionManager', None) +session_manager = cast('SessionManager', None) -ArgType = typing.Union[str, Sentinel] +ArgType = Union[str, Sentinel] def init(parent=None): @@ -80,7 +80,7 @@ def init(parent=None): session_manager = SessionManager(base_path, parent) -def shutdown(session: typing.Optional[ArgType], last_window: bool) -> None: +def shutdown(session: Optional[ArgType], last_window: bool) -> None: """Handle a shutdown by saving sessions and removing the autosave file.""" if session_manager is None: return # type: ignore @@ -153,7 +153,7 @@ class SessionManager(QObject): def __init__(self, base_path, parent=None): super().__init__(parent) - self.current = None # type: typing.Optional[str] + self.current: Optional[str] = None self._base_path = base_path self._last_window_session = None self.did_load = False @@ -196,9 +196,9 @@ class SessionManager(QObject): Return: A dict with the saved data for this item. """ - data = { + data: _JsonType = { 'url': bytes(item.url().toEncoded()).decode('ascii'), - } # type: _JsonType + } if item.title(): data['title'] = item.title() @@ -246,7 +246,7 @@ class SessionManager(QObject): tab: The WebView to save. active: Whether the tab is currently active. """ - data = {'history': []} # type: _JsonType + data: _JsonType = {'history': []} if active: data['active'] = True for idx, item in enumerate(tab.history): @@ -263,9 +263,9 @@ class SessionManager(QObject): def _save_all(self, *, only_window=None, with_private=False): """Get a dict with data for all windows/tabs.""" - data = {'windows': []} # type: _JsonType + data: _JsonType = {'windows': []} if only_window is not None: - winlist = [only_window] # type: typing.Iterable[int] + winlist: Iterable[int] = [only_window] else: winlist = objreg.window_registry @@ -282,7 +282,7 @@ class SessionManager(QObject): if tabbed_browser.is_private and not with_private: continue - win_data = {} # type: _JsonType + win_data: _JsonType = {} active_window = QApplication.instance().activeWindow() if getattr(active_window, 'win_id', None) == win_id: win_data['active'] = True @@ -377,7 +377,7 @@ class SessionManager(QObject): def _load_tab(self, new_tab, data): # noqa: C901 """Load yaml data into a newly opened tab.""" entries = [] - lazy_load = [] # type: typing.MutableSequence[_JsonType] + lazy_load: MutableSequence[_JsonType] = [] # use len(data['history']) # -> dropwhile empty if not session.lazy_session lazy_index = len(data['history']) @@ -436,10 +436,10 @@ class SessionManager(QObject): orig_url = url if histentry.get("last_visited"): - last_visited = QDateTime.fromString( + last_visited: Optional[QDateTime] = QDateTime.fromString( histentry.get("last_visited"), Qt.ISODate, - ) # type: typing.Optional[QDateTime] + ) else: last_visited = None diff --git a/qutebrowser/misc/throttle.py b/qutebrowser/misc/throttle.py index a8d24bd12..3540d8824 100644 --- a/qutebrowser/misc/throttle.py +++ b/qutebrowser/misc/throttle.py @@ -19,8 +19,8 @@ """A throttle for throttling function calls.""" -import typing import time +from typing import Any, Callable, Mapping, Optional, Sequence import attr from PyQt5.QtCore import QObject @@ -31,8 +31,8 @@ from qutebrowser.utils import usertypes @attr.s class _CallArgs: - args = attr.ib() # type: typing.Sequence[typing.Any] - kwargs = attr.ib() # type: typing.Mapping[str, typing.Any] + args: Sequence[Any] = attr.ib() + kwargs: Mapping[str, Any] = attr.ib() class Throttle(QObject): @@ -45,7 +45,7 @@ class Throttle(QObject): """ def __init__(self, - func: typing.Callable, + func: Callable, delay_ms: int, parent: QObject = None) -> None: """Constructor. @@ -59,8 +59,8 @@ class Throttle(QObject): super().__init__(parent) self._delay_ms = delay_ms self._func = func - self._pending_call = None # type: typing.Optional[_CallArgs] - self._last_call_ms = None # type: typing.Optional[int] + self._pending_call: Optional[_CallArgs] = None + self._last_call_ms: Optional[int] = None self._timer = usertypes.Timer(self, 'throttle-timer') self._timer.setSingleShot(True) @@ -71,7 +71,7 @@ class Throttle(QObject): self._pending_call = None self._last_call_ms = int(time.monotonic() * 1000) - def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Any: + def __call__(self, *args: Any, **kwargs: Any) -> Any: cur_time_ms = int(time.monotonic() * 1000) if self._pending_call is None: if (self._last_call_ms is None or diff --git a/qutebrowser/misc/utilcmds.py b/qutebrowser/misc/utilcmds.py index 8c2462b2b..56138c798 100644 --- a/qutebrowser/misc/utilcmds.py +++ b/qutebrowser/misc/utilcmds.py @@ -24,7 +24,7 @@ import functools import os import traceback -import typing +from typing import Optional from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication @@ -274,7 +274,7 @@ def version(win_id: int, paste: bool = False) -> None: pastebin_version() -_keytester_widget = None # type: typing.Optional[miscwidgets.KeyTesterWidget] +_keytester_widget: Optional[miscwidgets.KeyTesterWidget] = None @cmdutils.register(debug=True) |