mypy: Use explicit "type: ignore[...]" ignores

See #5368
This commit is contained in:
Florian Bruhin 2020-05-10 19:11:18 +02:00
parent 3f79308ffd
commit 341aa4ea75
70 changed files with 313 additions and 235 deletions

View File

@ -208,12 +208,12 @@ class argument: # noqa: N801,N806 pylint: disable=invalid-name
raise ValueError("{} has no argument {}!".format(funcname,
self._argname))
if not hasattr(func, 'qute_args'):
func.qute_args = {} # type: ignore
elif func.qute_args is None: # type: ignore
func.qute_args = {} # type: ignore[attr-defined]
elif func.qute_args is None: # type: ignore[attr-defined]
raise ValueError("@cmdutils.argument got called above (after) "
"@cmdutils.register for {}!".format(funcname))
arginfo = command.ArgInfo(**self._kwargs)
func.qute_args[self._argname] = arginfo # type: ignore
func.qute_args[self._argname] = arginfo # type: ignore[attr-defined]
return func

View File

@ -482,7 +482,7 @@ class Application(QApplication):
log.init.debug("Initializing application...")
self.launch_time = datetime.datetime.now()
self.focusObjectChanged.connect( # type: ignore
self.focusObjectChanged.connect( # type: ignore[attr-defined]
self.on_focus_object_changed)
self.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

View File

@ -541,7 +541,7 @@ class AbstractScroller(QObject):
@pyqtSlot()
def _log_scroll_pos_change(self) -> None:
log.webview.vdebug( # type: ignore
log.webview.vdebug( # type: ignore[attr-defined]
"Scroll position changed to {}".format(self.pos_px()))
def _init_widget(self, widget: QWidget) -> None:
@ -956,7 +956,7 @@ class AbstractTab(QWidget):
log.webview.warning("Unable to find event target!")
return
evt.posted = True # type: ignore
evt.posted = True # type: ignore[attr-defined]
QApplication.postEvent(recipient, evt)
def navigation_blocked(self) -> bool:
@ -1139,7 +1139,8 @@ class AbstractTab(QWidget):
def __repr__(self) -> str:
try:
qurl = self.url()
url = qurl.toDisplayString(QUrl.EncodeUnicode) # type: ignore
url = qurl.toDisplayString(
QUrl.EncodeUnicode) # type: ignore[arg-type]
except (AttributeError, RuntimeError) as exc:
url = '<{}>'.format(exc.__class__.__name__)
else:

View File

@ -647,11 +647,12 @@ class CommandDispatcher:
def _yank_url(self, what):
"""Helper method for yank() to get the URL to copy."""
assert what in ['url', 'pretty-url'], what
flags = QUrl.RemovePassword
if what == 'pretty-url':
flags |= QUrl.DecodeReserved # type: ignore
flags = QUrl.RemovePassword | QUrl.DecodeReserved
else:
flags |= QUrl.FullyEncoded # type: ignore
flags = QUrl.RemovePassword | QUrl.FullyEncoded
url = QUrl(self._current_url())
url_query = QUrlQuery()
url_query_str = urlutils.query_string(url)
@ -662,7 +663,7 @@ class CommandDispatcher:
if key in config.val.url.yank_ignored_parameters:
url_query.removeQueryItem(key)
url.setQuery(url_query)
return url.toString(flags) # type: ignore
return url.toString(flags) # type: ignore[arg-type]
@cmdutils.register(instance='command-dispatcher', scope='window')
@cmdutils.argument('what', choices=['selection', 'url', 'pretty-url',

View File

@ -105,7 +105,7 @@ class DownloadView(QListView):
def __repr__(self):
model = self.model()
if model is None:
count = 'None' # type: ignore
count = 'None' # type: ignore[unreachable]
else:
count = model.rowCount()
return utils.get_repr(self, count=count)

View File

@ -235,7 +235,7 @@ class HintActions:
flags = QUrl.FullyEncoded | QUrl.RemovePassword
if url.scheme() == 'mailto':
flags |= QUrl.RemoveScheme
urlstr = url.toString(flags) # type: ignore
urlstr = url.toString(flags) # type: ignore[arg-type]
new_content = urlstr
@ -256,14 +256,15 @@ class HintActions:
def run_cmd(self, url: QUrl, context: HintContext) -> None:
"""Run the command based on a hint URL."""
urlstr = url.toString(QUrl.FullyEncoded) # type: ignore
urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type]
args = context.get_args(urlstr)
commandrunner = runners.CommandRunner(self._win_id)
commandrunner.run_safely(' '.join(args))
def preset_cmd_text(self, url: QUrl, context: HintContext) -> None:
"""Preset a commandline text based on a hint URL."""
urlstr = url.toDisplayString(QUrl.FullyEncoded) # type: ignore
flags = QUrl.FullyEncoded
urlstr = url.toDisplayString(flags) # type: ignore[arg-type]
args = context.get_args(urlstr)
text = ' '.join(args)
if text[0] not in modeparsers.STARTCHARS:
@ -308,7 +309,8 @@ class HintActions:
}
url = elem.resolve_url(context.baseurl)
if url is not None:
env['QUTE_URL'] = url.toString(QUrl.FullyEncoded) # type: ignore
flags = QUrl.FullyEncoded
env['QUTE_URL'] = url.toString(flags) # type: ignore[arg-type]
try:
userscripts.run_async(context.tab, cmd, *args, win_id=self._win_id,
@ -328,7 +330,7 @@ class HintActions:
context: The HintContext to use.
"""
urlstr = url.toString(
QUrl.FullyEncoded | QUrl.RemovePassword) # type: ignore
QUrl.FullyEncoded | QUrl.RemovePassword) # type: ignore[arg-type]
args = context.get_args(urlstr)
commandrunner = runners.CommandRunner(self._win_id)
commandrunner.run_safely('spawn ' + ' '.join(args))

View File

@ -162,8 +162,8 @@ def _find_prevnext(prev, elems):
# pylint: disable=bad-config-option
for regex in getattr(config.val.hints, option):
# pylint: enable=bad-config-option
log.hints.vdebug("== Checking regex '{}'." # type: ignore
.format(regex.pattern))
log.hints.vdebug( # type: ignore[attr-defined]
"== Checking regex '{}'.".format(regex.pattern))
for e in elems:
text = str(e)
if not text:
@ -173,8 +173,8 @@ def _find_prevnext(prev, elems):
regex.pattern, text))
return e
else:
log.hints.vdebug("No match on '{}'!" # type: ignore
.format(text))
log.hints.vdebug( # type: ignore[attr-defined]
"No match on '{}'!".format(text))
return None

View File

@ -65,7 +65,9 @@ def _js_slot(*args):
# pylint: disable=protected-access
return self._error_con.callAsConstructor([e])
# pylint: enable=protected-access
return pyqtSlot(*args, result=QJSValue)(new_method) # type: ignore
deco = pyqtSlot(*args, result=QJSValue) # type: ignore[arg-type]
return deco(new_method)
return _decorator
@ -215,10 +217,10 @@ class PACResolver:
if from_file:
string_flags = QUrl.PrettyDecoded
else:
string_flags = QUrl.RemoveUserInfo # type: ignore
string_flags = QUrl.RemoveUserInfo # type: ignore[assignment]
if query.url().scheme() == 'https':
string_flags |= QUrl.RemovePath # type: ignore
string_flags |= QUrl.RemoveQuery # type: ignore
string_flags |= QUrl.RemovePath # type: ignore[assignment]
string_flags |= QUrl.RemoveQuery # type: ignore[assignment]
result = self._resolver.call([query.url().toString(string_flags),
query.peerHostName()])
@ -266,7 +268,8 @@ class PACFetcher(QObject):
"""Fetch the proxy from the remote URL."""
assert self._manager is not None
self._reply = self._manager.get(QNetworkRequest(self._pac_url))
self._reply.finished.connect(self._finish) # type: ignore
self._reply.finished.connect( # type: ignore[attr-defined]
self._finish)
@pyqtSlot()
def _finish(self):

View File

@ -52,7 +52,8 @@ def _warn_for_pac():
@pyqtSlot()
def shutdown():
QNetworkProxyFactory.setApplicationProxyFactory(None) # type: ignore
QNetworkProxyFactory.setApplicationProxyFactory(
None) # type: ignore[arg-type]
class ProxyFactory(QNetworkProxyFactory):
@ -71,6 +72,18 @@ class ProxyFactory(QNetworkProxyFactory):
else:
return None
def _set_capabilities(self, proxy):
if proxy.type() == QNetworkProxy.NoProxy:
return
capabilities = proxy.capabilities()
lookup_cap = QNetworkProxy.HostNameLookupCapability
if config.val.content.proxy_dns_requests:
capabilities |= lookup_cap
else:
capabilities &= ~lookup_cap
proxy.setCapabilities(capabilities)
def queryProxy(self, query):
"""Get the QNetworkProxies for a query.
@ -96,13 +109,6 @@ class ProxyFactory(QNetworkProxyFactory):
proxies = proxy.resolve(query)
else:
proxies = [proxy]
for p in proxies:
if p.type() != QNetworkProxy.NoProxy:
capabilities = p.capabilities()
lookup_cap = QNetworkProxy.HostNameLookupCapability
if config.val.content.proxy_dns_requests:
capabilities |= lookup_cap # type: ignore
else:
capabilities &= ~lookup_cap # type: ignore
p.setCapabilities(capabilities)
for proxy in proxies:
self._set_capabilities(proxy)
return proxies

View File

@ -84,6 +84,9 @@ def _generate_pdfjs_script(filename):
url_query.addQueryItem('filename', filename)
url.setQuery(url_query)
js_url = javascript.to_js(
url.toString(QUrl.FullyEncoded)) # type: ignore[arg-type]
return jinja.js_environment.from_string("""
document.addEventListener("DOMContentLoaded", function() {
if (typeof window.PDFJS !== 'undefined') {
@ -105,7 +108,7 @@ def _generate_pdfjs_script(filename):
viewer.open({{ url }});
});
""").render(
url=javascript.to_js(url.toString(QUrl.FullyEncoded)), # type: ignore
url=js_url,
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-70420
disable_create_object_url=(
not qtutils.version_check('5.12') and
@ -243,7 +246,7 @@ def get_main_url(filename: str, original_url: QUrl) -> QUrl:
query = QUrlQuery()
query.addQueryItem('filename', filename) # read from our JS
query.addQueryItem('file', '') # to avoid pdfjs opening the default PDF
urlstr = original_url.toString(QUrl.FullyEncoded) # type: ignore
urlstr = original_url.toString(QUrl.FullyEncoded) # type: ignore[arg-type]
query.addQueryItem('source', urlstr)
url.setQuery(query)
return url

View File

@ -39,7 +39,7 @@ try:
import secrets
except ImportError:
# New in Python 3.6
secrets = None # type: ignore
secrets = None # type: ignore[assignment]
from PyQt5.QtCore import QUrlQuery, QUrl, qVersion

View File

@ -392,7 +392,7 @@ class AbstractWebElement(collections.abc.MutableMapping):
window.show()
# FIXME:typing Why can't mypy determine the type of
# window.tabbed_browser?
window.tabbed_browser.tabopen(url) # type: ignore
window.tabbed_browser.tabopen(url) # type: ignore[has-type]
else:
raise ValueError("Unknown ClickTarget {}".format(click_target))

View File

@ -42,13 +42,15 @@ class DownloadItem(downloads.AbstractDownloadItem):
def __init__(self, qt_item: QWebEngineDownloadItem, parent=None):
super().__init__(parent)
self._qt_item = qt_item
qt_item.downloadProgress.connect( # type: ignore
qt_item.downloadProgress.connect( # type: ignore[attr-defined]
self.stats.on_download_progress)
qt_item.stateChanged.connect(self._on_state_changed) # type: ignore
qt_item.stateChanged.connect( # type: ignore[attr-defined]
self._on_state_changed)
# Ensure wrapped qt_item is deleted manually when the wrapper object
# is deleted. See https://github.com/qutebrowser/qutebrowser/issues/3373
self.destroyed.connect(self._qt_item.deleteLater) # type: ignore
self.destroyed.connect( # type: ignore[attr-defined]
self._qt_item.deleteLater)
def _is_page_download(self):
"""Check if this item is a page (i.e. mhtml) download."""
@ -93,7 +95,8 @@ class DownloadItem(downloads.AbstractDownloadItem):
"{}".format(state_name))
def _do_die(self):
self._qt_item.downloadProgress.disconnect() # type: ignore
progress_signal = self._qt_item.downloadProgress
progress_signal.disconnect() # type: ignore[attr-defined]
if self._qt_item.state() != QWebEngineDownloadItem.DownloadInterrupted:
self._qt_item.cancel()

View File

@ -248,7 +248,7 @@ class WebEngineElement(webelem.AbstractWebElement):
# (it does so with a 0ms QTimer...)
# This is also used in Qt's tests:
# https://github.com/qt/qtwebengine/commit/5e572e88efa7ba7c2b9138ec19e606d3e345ac90
QApplication.processEvents( # type: ignore
QApplication.processEvents( # type: ignore[call-overload]
QEventLoop.ExcludeSocketNotifiers |
QEventLoop.ExcludeUserInputEvents)

View File

@ -26,7 +26,7 @@ try:
from PyQt5.QtWebEngineCore import QWebEngineUrlScheme
except ImportError:
# Added in Qt 5.12
QWebEngineUrlScheme = None # type: ignore
QWebEngineUrlScheme = None # type: ignore[misc, assignment]
from qutebrowser.browser import qutescheme
from qutebrowser.utils import log, qtutils
@ -165,6 +165,7 @@ def init():
if QWebEngineUrlScheme is not None:
assert not QWebEngineUrlScheme.schemeByName(b'qute').name()
scheme = QWebEngineUrlScheme(b'qute')
scheme.setFlags(QWebEngineUrlScheme.LocalScheme | # type: ignore
QWebEngineUrlScheme.LocalAccessAllowed)
scheme.setFlags(
QWebEngineUrlScheme.LocalScheme | # type: ignore[arg-type]
QWebEngineUrlScheme.LocalAccessAllowed)
QWebEngineUrlScheme.registerScheme(scheme)

View File

@ -362,7 +362,8 @@ def _init_profiles():
default_profile = QWebEngineProfile.defaultProfile()
init_user_agent()
default_profile.setter = ProfileSetter(default_profile) # type: ignore
default_profile.setter = ProfileSetter( # type: ignore[attr-defined]
default_profile)
default_profile.setCachePath(
os.path.join(standarddir.cache(), 'webengine'))
default_profile.setPersistentStoragePath(
@ -372,7 +373,8 @@ def _init_profiles():
if not qtutils.is_single_process():
private_profile = QWebEngineProfile()
private_profile.setter = ProfileSetter(private_profile) # type: ignore
private_profile.setter = ProfileSetter( # type: ignore[attr-defined]
private_profile)
assert private_profile.isOffTheRecord()
private_profile.setter.init_profile()

View File

@ -125,7 +125,7 @@ class WebEngineAction(browsertab.AbstractAction):
tb = objreg.get('tabbed-browser', scope='window',
window=self._tab.win_id)
urlstr = self._tab.url().toString(
QUrl.RemoveUserInfo) # type: ignore
QUrl.RemoveUserInfo) # type: ignore[arg-type]
# The original URL becomes the path of a view-source: URL
# (without a host), but query/fragment should stay.
url = QUrl('view-source:' + urlstr)
@ -239,9 +239,11 @@ class WebEngineSearch(browsertab.AbstractSearch):
back yet.
"""
_NO_FLAGS = QWebEnginePage.FindFlags(0) # type: ignore[call-overload]
def __init__(self, tab, parent=None):
super().__init__(tab, parent)
self._flags = QWebEnginePage.FindFlags(0) # type: ignore
self._flags = self._NO_FLAGS
self._pending_searches = 0
# The API necessary to stop wrapping was added in this version
self._wrap_handler = _WebEngineSearchWrapHandler()
@ -296,7 +298,7 @@ class WebEngineSearch(browsertab.AbstractSearch):
return
self.text = text
self._flags = QWebEnginePage.FindFlags(0) # type: ignore
self._flags = self._NO_FLAGS
self._wrap_handler.reset_match_data()
self._wrap_handler.flag_wrap = wrap
if self._is_case_sensitive(ignore_case):
@ -315,7 +317,8 @@ class WebEngineSearch(browsertab.AbstractSearch):
def prev_result(self, *, result_cb=None):
# The int() here makes sure we get a copy of the flags.
flags = QWebEnginePage.FindFlags(int(self._flags)) # type: ignore
flags = QWebEnginePage.FindFlags(
int(self._flags)) # type: ignore[call-overload]
if flags & QWebEnginePage.FindBackward:
if self._wrap_handler.prevent_wrapping(going_up=False):
return
@ -1411,7 +1414,7 @@ class WebEngineTab(browsertab.AbstractTab):
title_url = QUrl(url)
title_url.setScheme('')
title_url_str = title_url.toDisplayString(
QUrl.RemoveScheme) # type: ignore
QUrl.RemoveScheme) # type: ignore[arg-type]
if title == title_url_str.strip('/'):
title = ""
@ -1433,12 +1436,15 @@ class WebEngineTab(browsertab.AbstractTab):
title="Proxy authentication required", text=msg,
mode=usertypes.PromptMode.user_pwd,
abort_on=[self.abort_questions], url=urlstr)
if answer is not None:
authenticator.setUser(answer.user)
authenticator.setPassword(answer.password)
else:
try:
sip.assign(authenticator, QAuthenticator()) # type: ignore
sip.assign( # type: ignore[attr-defined]
authenticator,
QAuthenticator())
except AttributeError:
self._show_error_page(url, "Proxy authentication required")
@ -1459,7 +1465,8 @@ class WebEngineTab(browsertab.AbstractTab):
if not netrc_success and answer is None:
log.network.debug("Aborting auth")
try:
sip.assign(authenticator, QAuthenticator()) # type: ignore
sip.assign( # type: ignore[attr-defined]
authenticator, QAuthenticator())
except AttributeError:
# WORKAROUND for
# https://www.riverbankcomputing.com/pipermail/pyqt/2016-December/038400.html
@ -1748,8 +1755,10 @@ class WebEngineTab(browsertab.AbstractTab):
page.loadFinished.connect(self._on_load_finished)
self.before_load_started.connect(self._on_before_load_started)
self.shutting_down.connect(self.abort_questions) # type: ignore
self.load_started.connect(self.abort_questions) # type: ignore
self.shutting_down.connect(
self.abort_questions) # type: ignore[arg-type]
self.load_started.connect(
self.abort_questions) # type: ignore[arg-type]
# pylint: disable=protected-access
self.audio._connect_signals()

View File

@ -95,7 +95,8 @@ class CookieJar(RAMCookieJar):
"""Parse cookies from lineparser and store them."""
cookies = [] # type: typing.Sequence[QNetworkCookie]
for line in self._lineparser:
cookies += QNetworkCookie.parseCookies(line) # type: ignore
line_cookies = QNetworkCookie.parseCookies(line)
cookies += line_cookies # type: ignore[operator]
self.setAllCookies(cookies)
def purge_old_cookies(self):
@ -105,7 +106,7 @@ class CookieJar(RAMCookieJar):
now = QDateTime.currentDateTime()
cookies = [c for c in self.allCookies()
if c.isSessionCookie() or
c.expirationDate() >= now] # type: ignore
c.expirationDate() >= now] # type: ignore[operator]
self.setAllCookies(cookies)
def save(self):

View File

@ -169,14 +169,15 @@ class NetworkManager(QNetworkAccessManager):
}
self._set_cookiejar()
self._set_cache()
self.sslErrors.connect(self.on_ssl_errors) # type: ignore
self.sslErrors.connect( # type: ignore[attr-defined]
self.on_ssl_errors)
self._rejected_ssl_errors = collections.defaultdict(
list) # type: _SavedErrorsType
self._accepted_ssl_errors = collections.defaultdict(
list) # type: _SavedErrorsType
self.authenticationRequired.connect( # type: ignore
self.authenticationRequired.connect( # type: ignore[attr-defined]
self.on_authentication_required)
self.proxyAuthenticationRequired.connect( # type: ignore
self.proxyAuthenticationRequired.connect( # type: ignore[attr-defined]
self.on_proxy_authentication_required)
self.netrc_used = False

View File

@ -59,12 +59,15 @@ class FixedDataNetworkReply(QNetworkReply):
# For some reason, a segfault will be triggered if these lambdas aren't
# there.
# pylint: disable=unnecessary-lambda
QTimer.singleShot(0, lambda:
self.metaDataChanged.emit()) # type: ignore
QTimer.singleShot(0, lambda:
self.readyRead.emit()) # type: ignore
QTimer.singleShot(0, lambda:
self.finished.emit()) # type: ignore
QTimer.singleShot(
0,
lambda: self.metaDataChanged.emit()) # type: ignore[attr-defined]
QTimer.singleShot(
0,
lambda: self.readyRead.emit()) # type: ignore[attr-defined]
QTimer.singleShot(
0,
lambda: self.finished.emit()) # type: ignore[attr-defined]
@pyqtSlot()
def abort(self):
@ -120,9 +123,9 @@ class ErrorNetworkReply(QNetworkReply):
self.setOpenMode(QIODevice.ReadOnly)
self.setError(error, errorstring)
QTimer.singleShot(0, lambda:
self.error.emit(error)) # type: ignore
self.error.emit(error)) # type: ignore[attr-defined]
QTimer.singleShot(0, lambda:
self.finished.emit()) # type: ignore
self.finished.emit()) # type: ignore[attr-defined]
def abort(self):
"""Do nothing since it's a fake reply."""
@ -150,7 +153,7 @@ class RedirectNetworkReply(QNetworkReply):
super().__init__(parent)
self.setAttribute(QNetworkRequest.RedirectionTargetAttribute, new_url)
QTimer.singleShot(0, lambda:
self.finished.emit()) # type: ignore
self.finished.emit()) # type: ignore[attr-defined]
def abort(self):
"""Called when there's e.g. a redirection limit."""

View File

@ -194,7 +194,7 @@ class WebKitElement(webelem.AbstractWebElement):
return None
text = utils.compact_text(self._elem.toOuterXml(), 500)
log.webelem.vdebug( # type: ignore
log.webelem.vdebug( # type: ignore[attr-defined]
"Client rectangles of element '{}': {}".format(text, rects))
for i in range(int(rects.get("length", 0))):

View File

@ -85,9 +85,11 @@ class WebKitSearch(browsertab.AbstractSearch):
"""QtWebKit implementations related to searching on the page."""
_NO_FLAGS = QWebPage.FindFlags(0) # type: ignore[call-overload]
def __init__(self, tab, parent=None):
super().__init__(tab, parent)
self._flags = QWebPage.FindFlags(0) # type: ignore
self._flags = self._NO_FLAGS
def _call_cb(self, callback, found, text, flags, caller):
"""Call the given callback if it's non-None.
@ -139,7 +141,7 @@ class WebKitSearch(browsertab.AbstractSearch):
self.text = text
self.search_displayed = True
self._flags = QWebPage.FindFlags(0) # type: ignore
self._flags = self._NO_FLAGS
if self._is_case_sensitive(ignore_case):
self._flags |= QWebPage.FindCaseSensitively
if reverse:
@ -161,7 +163,8 @@ class WebKitSearch(browsertab.AbstractSearch):
def prev_result(self, *, result_cb=None):
self.search_displayed = True
# The int() here makes sure we get a copy of the flags.
flags = QWebPage.FindFlags(int(self._flags)) # type: ignore
flags = QWebPage.FindFlags(
int(self._flags)) # type: ignore[call-overload]
if flags & QWebPage.FindBackward:
flags &= ~QWebPage.FindBackward
else:

View File

@ -78,22 +78,24 @@ class BrowserPage(QWebPage):
self.setNetworkAccessManager(self._networkmanager)
self.setForwardUnsupportedContent(True)
self.reloading.connect(self._networkmanager.clear_rejected_ssl_errors)
self.printRequested.connect( # type: ignore
self.printRequested.connect( # type: ignore[attr-defined]
self.on_print_requested)
self.downloadRequested.connect( # type: ignore
self.downloadRequested.connect( # type: ignore[attr-defined]
self.on_download_requested)
self.unsupportedContent.connect( # type: ignore
self.unsupportedContent.connect( # type: ignore[attr-defined]
self.on_unsupported_content)
self.loadStarted.connect(self.on_load_started) # type: ignore
self.featurePermissionRequested.connect( # type: ignore
self.loadStarted.connect( # type: ignore[attr-defined]
self.on_load_started)
self.featurePermissionRequested.connect( # type: ignore[attr-defined]
self._on_feature_permission_requested)
self.saveFrameStateRequested.connect( # type: ignore
self.saveFrameStateRequested.connect( # type: ignore[attr-defined]
self.on_save_frame_state_requested)
self.restoreFrameStateRequested.connect( # type: ignore
self.restoreFrameStateRequested.connect( # type: ignore[attr-defined]
self.on_restore_frame_state_requested)
self.loadFinished.connect( # type: ignore
self.loadFinished.connect( # type: ignore[attr-defined]
functools.partial(self._inject_userjs, self.mainFrame()))
self.frameCreated.connect(self._connect_userjs_signals) # type: ignore
self.frameCreated.connect( # type: ignore[attr-defined]
self._connect_userjs_signals)
@pyqtSlot('QWebFrame*')
def _connect_userjs_signals(self, frame):
@ -206,8 +208,10 @@ class BrowserPage(QWebPage):
suggested_file = ""
if info.suggestedFileNames:
suggested_file = info.suggestedFileNames[0]
files.fileNames, _ = QFileDialog.getOpenFileNames(
None, None, suggested_file) # type: ignore
None, None, suggested_file) # type: ignore[arg-type]
return True
def shutdown(self):

View File

@ -87,7 +87,8 @@ class WebView(QWebView):
stylesheet.set_register(self)
def __repr__(self):
urlstr = self.url().toDisplayString(QUrl.EncodeUnicode) # type: ignore
flags = QUrl.EncodeUnicode
urlstr = self.url().toDisplayString(flags) # type: ignore[arg-type]
url = utils.elide(urlstr, 100)
return utils.get_repr(self, tab_id=self._tab_id, url=url)
@ -97,7 +98,7 @@ class WebView(QWebView):
# Copied from:
# https://code.google.com/p/webscraping/source/browse/webkit.py#325
try:
self.setPage(None) # type: ignore
self.setPage(None) # type: ignore[arg-type]
except RuntimeError:
# It seems sometimes Qt has already deleted the QWebView and we
# get: RuntimeError: wrapped C/C++ object of type WebView has been
@ -180,9 +181,9 @@ class WebView(QWebView):
This is not needed for QtWebEngine, so it's in here.
"""
menu = self.page().createStandardContextMenu()
self.shutting_down.connect(menu.close) # type: ignore
self.shutting_down.connect(menu.close) # type: ignore[arg-type]
mm = modeman.instance(self.win_id)
mm.entered.connect(menu.close) # type: ignore
mm.entered.connect(menu.close) # type: ignore[arg-type]
menu.exec_(e.globalPos())
def showEvent(self, e):

View File

@ -244,7 +244,7 @@ class Command:
args = self._param_to_argparse_args(param, is_bool)
callsig = debug_utils.format_call(self.parser.add_argument, args,
kwargs, full=False)
log.commands.vdebug( # type: ignore
log.commands.vdebug( # type: ignore[attr-defined]
'Adding arg {} of type {} -> {}'
.format(param.name, typ, callsig))
self.parser.add_argument(*args, **kwargs)
@ -409,7 +409,8 @@ class Command:
if hasattr(typing, 'UnionMeta'):
# Python 3.5.2
# pylint: disable=no-member,useless-suppression
is_union = isinstance(typ, typing.UnionMeta) # type: ignore
is_union = isinstance(
typ, typing.UnionMeta) # type: ignore[attr-defined]
else:
is_union = getattr(typ, '__origin__', None) is typing.Union
@ -575,7 +576,7 @@ class Command:
def register(self):
"""Register this command in objects.commands."""
log.commands.vdebug( # type: ignore
log.commands.vdebug( # type: ignore[attr-defined]
"Registering command {} (from {}:{})".format(
self.name, self.handler.__module__, self.handler.__qualname__))
if self.name in objects.commands:

View File

@ -94,7 +94,7 @@ def _init_variable_replacements() -> typing.Mapping[str, _ReplacementFunction]:
modified_key = '{' + key + '}'
# x = modified_key is to avoid binding x as a closure
replacements[modified_key] = (
lambda _, x=modified_key: x) # type: ignore
lambda _, x=modified_key: x) # type: ignore[misc]
return replacements

View File

@ -62,7 +62,8 @@ class _QtFIFOReader(QObject):
self._fifo = os.fdopen(fd, 'r')
self._notifier = QSocketNotifier(typing.cast(sip.voidptr, fd),
QSocketNotifier.Read, self)
self._notifier.activated.connect(self.read_line) # type: ignore
self._notifier.activated.connect( # type: ignore[attr-defined]
self.read_line)
@pyqtSlot()
def read_line(self):
@ -265,7 +266,7 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner):
return
self._reader = _QtFIFOReader(self._filepath)
self._reader.got_line.connect(self.got_cmd) # type: ignore
self._reader.got_line.connect(self.got_cmd) # type: ignore[arg-type]
@pyqtSlot()
def on_proc_finished(self):

View File

@ -290,7 +290,7 @@ class CompletionItemDelegate(QStyledItemDelegate):
size = self._style.sizeFromContents(QStyle.CT_ItemViewItem, self._opt,
docsize, self._opt.widget)
qtutils.ensure_valid(size)
return size + QSize(10, 3) # type: ignore
return size + QSize(10, 3) # type: ignore[operator]
def paint(self, painter, option, index):
"""Override the QStyledItemDelegate paint function.

View File

@ -278,7 +278,7 @@ class CompletionView(QTreeView):
selmodel.setCurrentIndex(
idx,
QItemSelectionModel.ClearAndSelect | # type: ignore
QItemSelectionModel.ClearAndSelect | # type: ignore[arg-type]
QItemSelectionModel.Rows)
# if the last item is focused, try to fetch more

View File

@ -183,11 +183,13 @@ class CompletionModel(QAbstractItemModel):
# WORKAROUND:
# layoutChanged is broken in PyQt 5.7.1, so we must use metaObject
# https://www.riverbankcomputing.com/pipermail/pyqt/2017-January/038483.html
self.metaObject().invokeMethod(self, # type: ignore
"layoutAboutToBeChanged")
meta = self.metaObject()
meta.invokeMethod(self, # type: ignore[misc, call-overload]
"layoutAboutToBeChanged")
for cat in self._categories:
cat.set_pattern(pattern)
self.metaObject().invokeMethod(self, "layoutChanged") # type: ignore
meta.invokeMethod(self, # type: ignore[misc, call-overload]
"layoutChanged")
def first_item(self):
"""Return the index of the first child (non-category) in the model."""

View File

@ -71,9 +71,10 @@ def _print_preview(tab: apitypes.Tab) -> None:
tab.printing.check_preview_support()
diag = QPrintPreviewDialog(tab)
diag.setAttribute(Qt.WA_DeleteOnClose)
diag.setWindowFlags(diag.windowFlags() | # type: ignore
Qt.WindowMaximizeButtonHint |
Qt.WindowMinimizeButtonHint)
diag.setWindowFlags(
diag.windowFlags() | # type: ignore[operator, arg-type]
Qt.WindowMaximizeButtonHint |
Qt.WindowMinimizeButtonHint)
diag.paintRequested.connect(functools.partial(
tab.printing.to_printer, callback=print_callback))
diag.exec_()

View File

@ -206,7 +206,7 @@ class KeyConfig:
'mode'.format(key, mode))
self._validate(key, mode)
log.keyboard.vdebug( # type: ignore
log.keyboard.vdebug( # type: ignore[attr-defined]
"Adding binding {} -> {} in mode {}.".format(key, command, mode))
bindings = self._config.get_mutable_obj('bindings.commands')

View File

@ -692,8 +692,8 @@ def read_config_py(filename: str, raising: bool = False) -> None:
basename = os.path.basename(filename)
module = types.ModuleType('config')
module.config = api # type: ignore
module.c = container # type: ignore
module.config = api # type: ignore[attr-defined]
module.c = container # type: ignore[attr-defined]
module.__file__ = filename
try:

View File

@ -703,8 +703,10 @@ class Bool(BaseType):
super().__init__(none_ok)
self.valid_values = ValidValues('true', 'false', generate_docs=False)
def to_py(self, value: typing.Optional[bool]) -> typing.Optional[bool]:
def to_py(self,
value: typing.Union[bool, str, None]) -> typing.Optional[bool]:
self._basic_py_validation(value, bool)
assert not isinstance(value, str)
return value
def from_str(self, value: str) -> typing.Optional[bool]:
@ -734,15 +736,15 @@ class BoolAsk(Bool):
super().__init__(none_ok)
self.valid_values = ValidValues('true', 'false', 'ask')
def to_py(self, # type: ignore
def to_py(self, # type: ignore[override]
value: typing.Union[bool, str]) -> typing.Union[bool, str, None]:
# basic validation unneeded if it's == 'ask' and done by Bool if we
# call super().to_py
if isinstance(value, str) and value.lower() == 'ask':
return 'ask'
return super().to_py(value) # type: ignore
return super().to_py(value)
def from_str(self, # type: ignore
def from_str(self, # type: ignore[override]
value: str) -> typing.Union[bool, str, None]:
# basic validation unneeded if it's == 'ask' and done by Bool if we
# call super().from_str
@ -1347,7 +1349,7 @@ class QtFont(FontBase):
families = self._parse_families(family_str)
if hasattr(font, 'setFamilies'):
# Added in Qt 5.13
font.setFamily(families.family) # type: ignore
font.setFamily(families.family) # type: ignore[arg-type]
font.setFamilies(list(families))
else: # pragma: no cover
font.setFamily(families.to_str(quote=False))
@ -1832,7 +1834,7 @@ class Padding(Dict):
fixed_keys=['top', 'bottom', 'left', 'right'],
none_ok=none_ok)
def to_py( # type: ignore
def to_py( # type: ignore[override]
self,
value: typing.Union[usertypes.Unset, typing.Dict, None],
) -> typing.Union[usertypes.Unset, PaddingValues]:

View File

@ -109,7 +109,7 @@ class _StyleSheetObserver(QObject):
def register(self) -> None:
"""Do a first update and listen for more."""
qss = self._get_stylesheet()
log.config.vdebug( # type: ignore
log.config.vdebug( # type: ignore[attr-defined]
"stylesheet for {}: {}".format(self._obj.__class__.__name__, qss))
self._obj.setStyleSheet(qss)
if self._update:

View File

@ -103,6 +103,9 @@ class AbstractSettings:
def __init__(self, settings: typing.Any) -> None:
self._settings = settings
def _assert_not_unset(self, value: typing.Any) -> None:
assert value is not usertypes.UNSET
def set_attribute(self, name: str, value: typing.Any) -> bool:
"""Set the given QWebSettings/QWebEngineSettings attribute.
@ -139,7 +142,7 @@ class AbstractSettings:
Return:
True if there was a change, False otherwise.
"""
assert value is not usertypes.UNSET # type: ignore
self._assert_not_unset(value)
family = self._FONT_SIZES[name]
old_value = self._settings.fontSize(family)
self._settings.setFontSize(family, value)
@ -154,7 +157,7 @@ class AbstractSettings:
Return:
True if there was a change, False otherwise.
"""
assert value is not usertypes.UNSET # type: ignore
self._assert_not_unset(value)
family = self._FONT_FAMILIES[name]
if value is None:
font = QFont()
@ -172,7 +175,7 @@ class AbstractSettings:
Return:
True if there was a change, False otherwise.
"""
assert encoding is not usertypes.UNSET # type: ignore
self._assert_not_unset(encoding)
old_value = self._settings.defaultTextEncoding()
self._settings.setDefaultTextEncoding(encoding)
return old_value != encoding

View File

@ -82,8 +82,8 @@ def add_module_info(module: types.ModuleType) -> ModuleInfo:
"""Add ModuleInfo to a module (if not added yet)."""
# pylint: disable=protected-access
if not hasattr(module, '__qute_module_info'):
module.__qute_module_info = ModuleInfo() # type: ignore
return module.__qute_module_info # type: ignore
module.__qute_module_info = ModuleInfo() # type: ignore[attr-defined]
return module.__qute_module_info # type: ignore[attr-defined]
def load_components(*, skip_hooks: bool = False) -> None:
@ -109,7 +109,7 @@ def _walk_normal() -> typing.Iterator[ExtensionInfo]:
for _finder, name, ispkg in pkgutil.walk_packages(
# Only packages have a __path__ attribute,
# but we're sure this is one.
path=components.__path__, # type: ignore
path=components.__path__, # type: ignore[attr-defined]
prefix=components.__name__ + '.',
onerror=_on_walk_error):
if ispkg:

View File

@ -171,7 +171,8 @@ def _assert_plain_key(key: Qt.Key) -> None:
def _assert_plain_modifier(key: _ModifierType) -> None:
"""Make sure this is a modifier without a key mixed in."""
assert not key & ~Qt.KeyboardModifierMask, hex(key) # type: ignore
mask = Qt.KeyboardModifierMask
assert not key & ~mask, hex(key) # type: ignore[operator]
def _is_printable(key: Qt.Key) -> bool:
@ -285,8 +286,9 @@ def _modifiers_to_string(modifiers: _ModifierType) -> str:
modifier.
"""
_assert_plain_modifier(modifiers)
if modifiers & Qt.GroupSwitchModifier: # type: ignore
modifiers &= ~Qt.GroupSwitchModifier # type: ignore
altgr = Qt.GroupSwitchModifier
if modifiers & altgr: # type: ignore[operator]
modifiers &= ~altgr # type: ignore[operator, assignment]
result = 'AltGr+'
else:
result = ''
@ -453,7 +455,7 @@ class KeyInfo:
return ''
text = QKeySequence(self.key).toString()
if not self.modifiers & Qt.ShiftModifier: # type: ignore
if not self.modifiers & Qt.ShiftModifier: # type: ignore[operator]
text = text.lower()
return text
@ -510,7 +512,7 @@ class KeySequence:
"""Iterate over KeyInfo objects."""
for key_and_modifiers in self._iter_keys():
key = Qt.Key(int(key_and_modifiers) & ~Qt.KeyboardModifierMask)
modifiers = Qt.KeyboardModifiers( # type: ignore
modifiers = Qt.KeyboardModifiers( # type: ignore[call-overload]
int(key_and_modifiers) & Qt.KeyboardModifierMask)
yield KeyInfo(key=key, modifiers=modifiers)
@ -650,7 +652,7 @@ class KeySequence:
if (modifiers == Qt.ShiftModifier and
_is_printable(key) and
not ev.text().isupper()):
modifiers = Qt.KeyboardModifiers() # type: ignore
modifiers = Qt.KeyboardModifiers() # type: ignore[assignment]
# On macOS, swap Ctrl and Meta back
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-51293

View File

@ -245,10 +245,11 @@ class ModeManager(QObject):
"{}".format(curmode, utils.qualname(parser)))
match = parser.handle(event, dry_run=dry_run)
is_non_alnum = (
event.modifiers() not in [Qt.NoModifier, # type: ignore
Qt.ShiftModifier] or
not event.text().strip())
has_modifier = event.modifiers() not in [
Qt.NoModifier,
Qt.ShiftModifier,
] # type: ignore[comparison-overlap]
is_non_alnum = has_modifier or not event.text().strip()
forward_unbound_keys = config.cache['input.forward_unbound_keys']

View File

@ -102,7 +102,7 @@ def raise_window(window, alert=True):
window.setWindowState(window.windowState() | Qt.WindowActive)
window.raise_()
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-69568
QCoreApplication.processEvents( # type: ignore
QCoreApplication.processEvents( # type: ignore[call-overload]
QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
window.activateWindow()
@ -384,7 +384,9 @@ class MainWindow(QWidget):
self._command_dispatcher,
command_only=True,
scope='window', window=self.win_id)
self.tabbed_browser.widget.destroyed.connect( # type: ignore
widget = self.tabbed_browser.widget
widget.destroyed.connect( # type: ignore[attr-defined]
functools.partial(objreg.delete, 'command-dispatcher',
scope='window', window=self.win_id))
@ -491,15 +493,15 @@ class MainWindow(QWidget):
mode_manager.left.connect(self.status.on_mode_left)
mode_manager.left.connect(self.status.cmd.on_mode_left)
mode_manager.left.connect(
message.global_bridge.mode_left) # type: ignore
message.global_bridge.mode_left) # type: ignore[arg-type]
# commands
normal_parser = mode_manager.parsers[usertypes.KeyMode.normal]
normal_parser.keystring_updated.connect(
self.status.keystring.setText)
self.status.cmd.got_cmd[str].connect( # type: ignore
self.status.cmd.got_cmd[str].connect( # type: ignore[index]
self._commandrunner.run_safely)
self.status.cmd.got_cmd[str, int].connect( # type: ignore
self.status.cmd.got_cmd[str, int].connect( # type: ignore[index]
self._commandrunner.run_safely)
self.status.cmd.returnPressed.connect(
self.tabbed_browser.on_cmd_return_pressed)
@ -584,8 +586,8 @@ class MainWindow(QWidget):
if on:
self.state_before_fullscreen = self.windowState()
self.setWindowState(
Qt.WindowFullScreen | # type: ignore
self.state_before_fullscreen) # type: ignore
Qt.WindowFullScreen | # type: ignore[arg-type]
self.state_before_fullscreen) # type: ignore[operator]
elif self.isFullScreen():
self.setWindowState(self.state_before_fullscreen)
log.misc.debug('on: {}, state before fullscreen: {}'.format(

View File

@ -192,7 +192,7 @@ class PromptQueue(QObject):
if blocking:
loop = qtutils.EventLoop()
self._loops.append(loop)
loop.destroyed.connect( # type: ignore
loop.destroyed.connect( # type: ignore[attr-defined]
lambda: self._loops.remove(loop))
question.completed.connect(loop.quit)
question.completed.connect(loop.deleteLater)
@ -757,7 +757,7 @@ class FilenamePrompt(_BasePrompt):
selmodel.setCurrentIndex(
idx,
QItemSelectionModel.ClearAndSelect | # type: ignore
QItemSelectionModel.ClearAndSelect | # type: ignore[arg-type]
QItemSelectionModel.Rows)
self._insert_path(idx, clicked=False)
@ -784,7 +784,7 @@ class DownloadFilenamePrompt(FilenamePrompt):
def __init__(self, question, parent=None):
super().__init__(question, parent)
self._file_model.setFilter(
QDir.AllDirs | QDir.Drives | QDir.NoDot) # type: ignore
QDir.AllDirs | QDir.Drives | QDir.NoDot) # type: ignore[arg-type]
def accept(self, value=None, save=False):
done = super().accept(value, save)
@ -962,5 +962,5 @@ def init():
"""Initialize global prompt objects."""
global prompt_queue
prompt_queue = PromptQueue()
message.global_bridge.ask_question.connect( # type: ignore
message.global_bridge.ask_question.connect( # type: ignore[call-arg]
prompt_queue.ask_question, Qt.DirectConnection)

View File

@ -21,8 +21,8 @@
import enum
import attr
from PyQt5.QtCore import (pyqtSignal, pyqtSlot, pyqtProperty, # type: ignore
Qt, QSize, QTimer)
from PyQt5.QtCore import (pyqtSignal, pyqtSlot, # type: ignore[attr-defined]
pyqtProperty, Qt, QSize, QTimer)
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QStackedLayout, QSizePolicy
from qutebrowser.browser import browsertab

View File

@ -72,8 +72,9 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
self.cursorPositionChanged.connect(
self.update_completion) # type: ignore
self.textChanged.connect(self.update_completion) # type: ignore
self.update_completion) # type: ignore[arg-type]
self.textChanged.connect(
self.update_completion) # type: ignore[arg-type]
self.textChanged.connect(self.updateGeometry)
self.textChanged.connect(self._incremental_search)
@ -148,7 +149,7 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
raise cmdutils.CommandError(
"Invalid command text '{}'.".format(text))
if run_on_count and count is not None:
self.got_cmd[str, int].emit(text, count) # type: ignore
self.got_cmd[str, int].emit(text, count) # type: ignore[index]
else:
self.set_cmd_text(text)
@ -198,7 +199,7 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
'cmd accept')
if not was_search:
self.got_cmd[str].emit(text[1:]) # type: ignore
self.got_cmd[str].emit(text[1:]) # type: ignore[index]
@cmdutils.register(instance='status-command', scope='window')
def edit_command(self, run: bool = False) -> None:

View File

@ -21,7 +21,8 @@
import enum
from PyQt5.QtCore import pyqtSlot, pyqtProperty, QUrl # type: ignore
from PyQt5.QtCore import (pyqtSlot, pyqtProperty, # type: ignore[attr-defined]
QUrl)
from qutebrowser.mainwindow.statusbar import textbase
from qutebrowser.config import stylesheet

View File

@ -205,7 +205,8 @@ class TabbedBrowser(QWidget):
self._tab_insert_idx_right = -1
self.shutting_down = False
self.widget.tabCloseRequested.connect(self.on_tab_close_requested)
self.widget.new_tab_requested.connect(self.tabopen) # type: ignore
self.widget.new_tab_requested.connect(
self.tabopen) # type: ignore[arg-type]
self.widget.currentChanged.connect(self._on_current_changed)
self.cur_fullscreen_requested.connect(self.widget.tabBar().maybe_hide)
self.widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
@ -284,7 +285,7 @@ class TabbedBrowser(QWidget):
for i in range(self.widget.count()):
widget = self.widget.widget(i)
if widget is None:
log.webview.debug( # type: ignore
log.webview.debug( # type: ignore[unreachable]
"Got None-widget in tabbedbrowser!")
else:
widgets.append(widget)
@ -528,7 +529,7 @@ class TabbedBrowser(QWidget):
"""Close a tab via an index."""
tab = self.widget.widget(idx)
if tab is None:
log.webview.debug( # type: ignore
log.webview.debug( # type: ignore[unreachable]
"Got invalid tab {} for index {}!".format(tab, idx))
return
self.tab_close_prompt_if_pinned(
@ -800,7 +801,7 @@ class TabbedBrowser(QWidget):
"""Give focus to current tab if command mode was left."""
widget = self.widget.currentWidget()
if widget is None:
return # type: ignore
return # type: ignore[unreachable]
if mode in [usertypes.KeyMode.command] + modeman.PROMPT_MODES:
log.modes.debug("Left status-input mode, focusing {!r}".format(
widget))
@ -817,7 +818,7 @@ class TabbedBrowser(QWidget):
return
tab = self.widget.widget(idx)
if tab is None:
log.webview.debug( # type: ignore
log.webview.debug( # type: ignore[unreachable]
"on_current_changed got called with invalid index {}"
.format(idx))
return

View File

@ -60,7 +60,8 @@ class TabWidget(QTabWidget):
bar = TabBar(win_id, self)
self.setStyle(TabBarStyle())
self.setTabBar(bar)
bar.tabCloseRequested.connect(self.tabCloseRequested) # type: ignore
bar.tabCloseRequested.connect(
self.tabCloseRequested) # type: ignore[arg-type]
bar.tabMoved.connect(functools.partial(
QTimer.singleShot, 0, self.update_tab_titles))
bar.currentChanged.connect(self._on_current_changed)
@ -82,7 +83,7 @@ class TabWidget(QTabWidget):
position = config.val.tabs.position
selection_behavior = config.val.tabs.select_on_remove
self.setTabPosition(position)
tabbar.vertical = position in [ # type: ignore
tabbar.vertical = position in [ # type: ignore[attr-defined]
QTabWidget.West, QTabWidget.East]
tabbar.setSelectionBehaviorOnRemove(selection_behavior)
tabbar.refresh()
@ -164,7 +165,7 @@ class TabWidget(QTabWidget):
"""Get the tab field data."""
tab = self.widget(idx)
if tab is None:
log.misc.debug( # type: ignore
log.misc.debug( # type: ignore[unreachable]
"Got None-tab in get_tab_fields!")
page_title = self.page_title(idx)
@ -331,7 +332,7 @@ class TabWidget(QTabWidget):
"""
tab = self.widget(idx)
if tab is None:
url = QUrl() # type: ignore
url = QUrl() # type: ignore[unreachable]
else:
url = tab.url()
# It's possible for url to be invalid, but the caller will handle that.

View File

@ -55,7 +55,7 @@ class PyPIVersionClient(QObject):
self._client = httpclient.HTTPClient(self)
else:
self._client = client
self._client.error.connect(self.error) # type: ignore
self._client.error.connect(self.error) # type: ignore[arg-type]
self._client.success.connect(self.on_client_success)
def get_version(self, package='qutebrowser'):

View File

@ -30,12 +30,12 @@ try:
except ImportError: # pragma: no cover
try:
# Python2
from Tkinter import Tk # type: ignore
from Tkinter import Tk # type: ignore[import, no-redef]
import tkMessageBox as messagebox # type: ignore # noqa: N813
except ImportError:
# Some Python without Tk
Tk = None # type: ignore
messagebox = None # type: ignore
Tk = None # type: ignore[misc, assignment]
messagebox = None # type: ignore[assignment]
# First we check the version of Python. This code should run fine with python2
@ -49,7 +49,7 @@ def check_python_version():
version_str = '.'.join(map(str, sys.version_info[:3]))
text = ("At least Python 3.5.2 is required to run qutebrowser, but " +
"it's running with " + version_str + ".\n")
if (Tk and # type: ignore
if (Tk and # type: ignore[unreachable]
'--no-err-windows' not in sys.argv): # pragma: no cover
root = Tk()
root.withdraw()

View File

@ -532,7 +532,7 @@ class FatalCrashDialog(_CrashDialog):
if self._chk_history.isChecked():
try:
if history.web_history is None:
history_data = '<unavailable>' # type: ignore
history_data = '<unavailable>' # type: ignore[unreachable]
else:
history_data = '\n'.join(str(e) for e in
history.web_history.get_recent())
@ -629,7 +629,7 @@ class ReportErrorDialog(QDialog):
hbox = QHBoxLayout()
hbox.addStretch()
btn = QPushButton("Close")
btn.clicked.connect(self.close) # type: ignore
btn.clicked.connect(self.close) # type: ignore[arg-type]
hbox.addWidget(btn)
vbox.addLayout(hbox)

View File

@ -185,7 +185,7 @@ class CrashHandler(QObject):
if sys.__stderr__ is not None:
faulthandler.enable(sys.__stderr__)
else:
faulthandler.disable() # type: ignore
faulthandler.disable() # type: ignore[unreachable]
try:
self._crash_log_file.close()
os.remove(self._crash_log_file.name)
@ -355,7 +355,7 @@ class SignalHandler(QObject):
self._notifier = QSocketNotifier(typing.cast(sip.voidptr, read_fd),
QSocketNotifier.Read,
self)
self._notifier.activated.connect( # type: ignore
self._notifier.activated.connect( # type: ignore[attr-defined]
self.handle_signal_wakeup)
self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
# pylint: enable=import-error,no-member,useless-suppression

View File

@ -38,7 +38,7 @@ import datetime
try:
import tkinter
except ImportError:
tkinter = None # type: ignore
tkinter = None # type: ignore[assignment]
# NOTE: No qutebrowser or PyQt import should be done here, as some early
# initialization needs to take place before that!
@ -251,7 +251,8 @@ def configure_pyqt():
from PyQt5 import QtCore
QtCore.pyqtRemoveInputHook()
try:
QtCore.pyqt5_enable_new_onexit_scheme(True) # type: ignore
QtCore.pyqt5_enable_new_onexit_scheme( # type: ignore[attr-defined]
True)
except AttributeError:
# Added in PyQt 5.13 somewhere, going to be the default in 5.14
pass
@ -259,7 +260,7 @@ def configure_pyqt():
from qutebrowser.qt import sip
try:
# Added in sip 4.19.4
sip.enableoverflowchecking(True) # type: ignore
sip.enableoverflowchecking(True) # type: ignore[attr-defined]
except AttributeError:
pass

View File

@ -187,7 +187,7 @@ class ExternalEditor(QObject):
if not ok:
log.procs.error("Failed to watch path: {}"
.format(self._filename))
self._watcher.fileChanged.connect( # type: ignore
self._watcher.fileChanged.connect( # type: ignore[attr-defined]
self._on_file_changed)
args = [self._sub_placeholder(arg, line, column) for arg in editor[1:]]

View File

@ -63,11 +63,11 @@ class GUIProcess(QObject):
self._proc = QProcess(self)
self._proc.errorOccurred.connect(self._on_error)
self._proc.errorOccurred.connect(self.error) # type: ignore
self._proc.errorOccurred.connect(self.error) # type: ignore[arg-type]
self._proc.finished.connect(self._on_finished)
self._proc.finished.connect(self.finished) # type: ignore
self._proc.finished.connect(self.finished) # type: ignore[arg-type]
self._proc.started.connect(self._on_started)
self._proc.started.connect(self.started) # type: ignore
self._proc.started.connect(self.started) # type: ignore[arg-type]
if additional_env is not None:
procenv = QProcessEnvironment.systemEnvironment()
@ -163,7 +163,8 @@ class GUIProcess(QObject):
"""Convenience wrapper around QProcess::startDetached."""
log.procs.debug("Starting detached.")
self._pre_start(cmd, args)
ok, _pid = self._proc.startDetached(cmd, args, None) # type: ignore
ok, _pid = self._proc.startDetached(
cmd, args, None) # type: ignore[call-arg]
if not ok:
message.error("Error while spawning {}".format(self._what))

View File

@ -178,7 +178,7 @@ class IPCServer(QObject):
self._atime_timer.setTimerType(Qt.VeryCoarseTimer)
self._server = QLocalServer(self)
self._server.newConnection.connect( # type: ignore
self._server.newConnection.connect( # type: ignore[attr-defined]
self.handle_connection)
self._socket = None
@ -252,21 +252,24 @@ class IPCServer(QObject):
return
socket = self._server.nextPendingConnection()
if socket is None:
log.ipc.debug("No new connection to handle.") # type: ignore
log.ipc.debug( # type: ignore[unreachable]
"No new connection to handle.")
return
log.ipc.debug("Client connected (socket 0x{:x}).".format(id(socket)))
self._timer.start()
self._socket = socket
socket.readyRead.connect(self.on_ready_read) # type: ignore
socket.readyRead.connect( # type: ignore[attr-defined]
self.on_ready_read)
if socket.canReadLine():
log.ipc.debug("We can read a line immediately.")
self.on_ready_read()
socket.error.connect(self.on_error) # type: ignore
socket.error.connect(self.on_error) # type: ignore[attr-defined]
if socket.error() not in [QLocalSocket.UnknownSocketError,
QLocalSocket.PeerClosedError]:
log.ipc.debug("We got an error immediately.")
self.on_error(socket.error())
socket.disconnected.connect(self.on_disconnected) # type: ignore
socket.disconnected.connect( # type: ignore[attr-defined]
self.on_disconnected)
if socket.state() == QLocalSocket.UnconnectedState:
log.ipc.debug("Socket was disconnected immediately.")
self.on_disconnected()

View File

@ -37,7 +37,7 @@ class MinimalLineEditMixin:
"""A mixin to give a QLineEdit a minimal look and nicer repr()."""
def __init__(self):
self.setStyleSheet( # type: ignore
self.setStyleSheet( # type: ignore[attr-defined]
"""
QLineEdit {
border: 0px;
@ -46,7 +46,8 @@ class MinimalLineEditMixin:
}
"""
)
self.setAttribute(Qt.WA_MacShowFocusRect, False) # type: ignore
self.setAttribute( # type: ignore[attr-defined]
Qt.WA_MacShowFocusRect, False)
def keyPressEvent(self, e):
"""Override keyPressEvent to paste primary selection on Shift + Ins."""
@ -57,9 +58,9 @@ class MinimalLineEditMixin:
e.ignore()
else:
e.accept()
self.insert(text) # type: ignore
self.insert(text) # type: ignore[attr-defined]
return
super().keyPressEvent(e) # type: ignore
super().keyPressEvent(e) # type: ignore[misc]
def __repr__(self):
return utils.get_repr(self)
@ -260,7 +261,7 @@ class WrapperLayout(QLayout):
widget.setParent(container)
def unwrap(self):
self._widget.setParent(None) # type: ignore
self._widget.setParent(None) # type: ignore[call-overload]
self._widget.deleteLater()

View File

@ -323,7 +323,8 @@ class SessionManager(QObject):
else:
data = self._save_all(only_window=only_window,
with_private=with_private)
log.sessions.vdebug("Saving data: {}".format(data)) # type: ignore
log.sessions.vdebug( # type: ignore[attr-defined]
"Saving data: {}".format(data))
try:
with qtutils.savefile_open(path) as f:
utils.yaml_dump(data, f)

View File

@ -138,7 +138,8 @@ def split(s, keep=False):
out = []
spaces = ""
log.shlexer.vdebug("{!r} -> {!r}".format(s, tokens)) # type: ignore
log.shlexer.vdebug( # type: ignore[attr-defined]
"{!r} -> {!r}".format(s, tokens))
for t in tokens:
if t.isspace():

View File

@ -190,7 +190,8 @@ class Query:
raise BugError("Cannot iterate inactive query")
rec = self.query.record()
fields = [rec.fieldName(i) for i in range(rec.count())]
rowtype = collections.namedtuple('ResultRow', fields) # type: ignore
rowtype = collections.namedtuple( # type: ignore[misc]
'ResultRow', fields)
while self.query.next():
rec = self.query.record()

View File

@ -25,4 +25,4 @@
try:
from PyQt5 import sip
except ImportError:
import sip # type: ignore
import sip # type: ignore[import, no-redef]

View File

@ -80,7 +80,7 @@ def log_signals(obj: QObject) -> QObject:
pass
if inspect.isclass(obj):
old_init = obj.__init__ # type: ignore
old_init = obj.__init__ # type: ignore[misc]
@functools.wraps(old_init)
def new_init(self: typing.Any,
@ -90,7 +90,7 @@ def log_signals(obj: QObject) -> QObject:
old_init(self, *args, **kwargs)
connect_log_slot(self)
obj.__init__ = new_init # type: ignore
obj.__init__ = new_init # type: ignore[misc]
else:
connect_log_slot(obj)
@ -122,7 +122,7 @@ def qenum_key(base: typing.Type,
try:
idx = base.staticMetaObject.indexOfEnumerator(klass.__name__)
meta_enum = base.staticMetaObject.enumerator(idx)
ret = meta_enum.valueToKey(int(value)) # type: ignore
ret = meta_enum.valueToKey(int(value)) # type: ignore[arg-type]
except AttributeError:
ret = None
@ -132,7 +132,7 @@ def qenum_key(base: typing.Type,
ret = name
break
else:
ret = '0x{:04x}'.format(int(value)) # type: ignore
ret = '0x{:04x}'.format(int(value)) # type: ignore[arg-type]
if add_base and hasattr(base, '__name__'):
return '.'.join([base.__name__, ret])
@ -175,7 +175,7 @@ def qflags_key(base: typing.Type,
bits = []
names = []
mask = 0x01
value = int(value) # type: ignore
value = int(value) # type: ignore[arg-type]
while mask <= value:
if value & mask:
bits.append(mask)
@ -183,7 +183,8 @@ def qflags_key(base: typing.Type,
for bit in bits:
# We have to re-convert to an enum type here or we'll sometimes get an
# empty string back.
names.append(qenum_key(base, klass(bit), add_base)) # type: ignore
enum_value = klass(bit) # type: ignore[call-arg]
names.append(qenum_key(base, enum_value, add_base))
return '|'.join(names)
@ -209,14 +210,14 @@ def signal_name(sig: pyqtSignal) -> str:
# sig.signal == '2signal1'
# sig.signal == '2signal2(QString,QString)'
m = re.fullmatch(r'[0-9]+(?P<name>.*)\(.*\)',
sig.signal) # type: ignore
sig.signal) # type: ignore[attr-defined]
elif hasattr(sig, 'signatures'):
# Unbound signal, PyQt >= 5.11
# Examples:
# sig.signatures == ('signal1()',)
# sig.signatures == ('signal2(QString,QString)',)
m = re.fullmatch(r'(?P<name>.*)\(.*\)',
sig.signatures[0]) # type: ignore
sig.signatures[0]) # type: ignore[attr-defined]
else: # pragma: no cover
# Unbound signal, PyQt < 5.11
# Examples:

View File

@ -112,7 +112,7 @@ class Environment(jinja2.Environment):
"""
image = utils.resource_filename(path)
url = QUrl.fromLocalFile(image)
urlstr = url.toString(QUrl.FullyEncoded) # type: ignore
urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type]
return urlstr
def _data_url(self, path: str) -> str:
@ -156,11 +156,11 @@ def template_config_variables(template: str) -> typing.FrozenSet[str]:
# For example it's ['ab', 'c', 'd'] for 'conf.d.c.ab'.
attrlist = [] # type: typing.List[str]
while isinstance(node, jinja2.nodes.Getattr):
attrlist.append(node.attr) # type: ignore
node = node.node # type: ignore
attrlist.append(node.attr) # type: ignore[attr-defined]
node = node.node # type: ignore[attr-defined]
if isinstance(node, jinja2.nodes.Name):
if node.name == 'conf': # type: ignore
if node.name == 'conf': # type: ignore[attr-defined]
result.add('.'.join(reversed(attrlist)))
# otherwise, the node is a Name node so it doesn't have any
# child nodes

View File

@ -81,10 +81,10 @@ LOG_COLORS = {
# mypy doesn't know about this, so we need to ignore it.
VDEBUG_LEVEL = 9
logging.addLevelName(VDEBUG_LEVEL, 'VDEBUG')
logging.VDEBUG = VDEBUG_LEVEL # type: ignore
logging.VDEBUG = VDEBUG_LEVEL # type: ignore[attr-defined]
LOG_LEVELS = {
'VDEBUG': logging.VDEBUG, # type: ignore
'VDEBUG': logging.VDEBUG, # type: ignore[attr-defined]
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
@ -109,7 +109,7 @@ def vdebug(self: logging.Logger,
# pylint: enable=protected-access
logging.Logger.vdebug = vdebug # type: ignore
logging.Logger.vdebug = vdebug # type: ignore[attr-defined]
# The different loggers used.
@ -278,7 +278,7 @@ def _init_handlers(
level, color, force_color, json_logging)
if sys.stderr is None:
console_handler = None # type: ignore
console_handler = None # type: ignore[unreachable]
else:
strip = False if force_color else None
if use_colorama:
@ -337,14 +337,17 @@ def _init_formatters(
use_colors=False)
html_formatter = HTMLFormatter(EXTENDED_FMT_HTML, DATEFMT,
log_colors=LOG_COLORS)
use_colorama = False
if sys.stderr is None:
return None, ram_formatter, html_formatter, False # type: ignore
console_formatter = None # type: ignore[unreachable]
return console_formatter, ram_formatter, html_formatter, use_colorama
if json_logging:
json_formatter = JSONFormatter()
return json_formatter, ram_formatter, html_formatter, False
return json_formatter, ram_formatter, html_formatter, use_colorama
use_colorama = False
color_supported = os.name == 'posix' or colorama
if color_supported and (sys.stderr.isatty() or force_color) and color:
@ -481,13 +484,13 @@ def qt_message_handler(msg_type: QtCore.QtMsgType,
level = qt_to_logging[msg_type]
if context.function is None:
func = 'none' # type: ignore
func = 'none' # type: ignore[unreachable]
elif ':' in context.function:
func = '"{}"'.format(context.function)
else:
func = context.function
if (context.category is None or # type: ignore
if (context.category is None or # type: ignore[unreachable]
context.category == 'default'):
name = 'qt'
else:
@ -692,9 +695,10 @@ class HTMLFormatter(logging.Formatter):
record_clone.__dict__.update(self._colordict)
if record_clone.levelname in self._log_colors:
color = self._log_colors[record_clone.levelname]
record_clone.log_color = self._colordict[color] # type: ignore
color_str = self._colordict[color]
record_clone.log_color = color_str # type: ignore[attr-defined]
else:
record_clone.log_color = '' # type: ignore
record_clone.log_color = '' # type: ignore[attr-defined]
for field in ['msg', 'filename', 'funcName', 'levelname', 'module',
'name', 'pathname', 'processName', 'threadName']:
data = str(getattr(record_clone, field))

View File

@ -86,7 +86,7 @@ class ObjectRegistry(collections.UserDict):
if isinstance(obj, QObject):
func = functools.partial(self.on_destroyed, name)
obj.destroyed.connect(func) # type: ignore
obj.destroyed.connect(func) # type: ignore[attr-defined]
self._partial_objs[name] = func
super().__setitem__(name, obj)

View File

@ -42,7 +42,7 @@ from PyQt5.QtWidgets import QApplication
try:
from PyQt5.QtWebKit import qWebKitVersion
except ImportError: # pragma: no cover
qWebKitVersion = None # type: ignore # noqa: N816
qWebKitVersion = None # type: ignore[assignment] # noqa: N816
if typing.TYPE_CHECKING:
from PyQt5.QtCore import QFileDevice
@ -203,7 +203,7 @@ def serialize_stream(stream: QDataStream, obj: _QtSerializableType) -> None:
"""Serialize an object into a QDataStream."""
# pylint: disable=pointless-statement
check_qdatastream(stream)
stream << obj # type: ignore
stream << obj # type: ignore[operator]
check_qdatastream(stream)
@ -211,7 +211,7 @@ def deserialize_stream(stream: QDataStream, obj: _QtSerializableType) -> None:
"""Deserialize a QDataStream into an object."""
# pylint: disable=pointless-statement
check_qdatastream(stream)
stream >> obj # type: ignore
stream >> obj # type: ignore[operator]
check_qdatastream(stream)
@ -426,7 +426,7 @@ class QtValueError(ValueError):
def __init__(self, obj: 'Validatable') -> None:
try:
self.reason = obj.errorString() # type: ignore
self.reason = obj.errorString() # type: ignore[attr-defined]
except AttributeError:
self.reason = None
err = "{} is not valid".format(obj)

View File

@ -68,7 +68,7 @@ def _unset_organization() -> typing.Iterator[None]:
qapp = QApplication.instance()
if qapp is not None:
orgname = qapp.organizationName()
qapp.setOrganizationName(None) # type: ignore
qapp.setOrganizationName(None) # type: ignore[arg-type]
try:
yield
finally:

View File

@ -125,9 +125,9 @@ def _get_search_url(txt: str) -> QUrl:
url = qurl_from_user_input(evaluated)
else:
url = qurl_from_user_input(config.val.url.searchengines[engine])
url.setPath(None) # type: ignore
url.setFragment(None) # type: ignore
url.setQuery(None) # type: ignore
url.setPath(None) # type: ignore[arg-type]
url.setFragment(None) # type: ignore[arg-type]
url.setQuery(None) # type: ignore[call-overload]
qtutils.ensure_valid(url)
return url
@ -522,14 +522,14 @@ def encoded_url(url: QUrl) -> str:
return url.toEncoded().data().decode('ascii')
def file_url(path: str) -> QUrl:
def file_url(path: str) -> str:
"""Return a file:// url (as string) to the given local path.
Arguments:
path: The absolute path to the local file
"""
url = QUrl.fromLocalFile(path)
return url.toString(QUrl.FullyEncoded) # type: ignore
return url.toString(QUrl.FullyEncoded) # type: ignore[arg-type]
def data_url(mimetype: str, data: bytes) -> QUrl:

View File

@ -91,7 +91,7 @@ class NeighborList(typing.Sequence[_T]):
self._mode = mode
self.fuzzyval = None # type: typing.Optional[int]
def __getitem__(self, key: int) -> _T: # type: ignore
def __getitem__(self, key: int) -> _T: # type: ignore[override]
return self._items[key]
def __len__(self) -> int:
@ -120,7 +120,8 @@ class NeighborList(typing.Sequence[_T]):
if items:
item = min(
items,
key=lambda tpl: abs(self.fuzzyval - tpl[1])) # type: ignore
key=lambda tpl:
abs(self.fuzzyval - tpl[1])) # type: ignore[operator]
else:
sorted_items = sorted(enumerate(self.items), key=lambda e: e[1])
idx = 0 if offset < 0 else -1

View File

@ -47,7 +47,7 @@ try:
CSafeDumper as YamlDumper)
YAML_C_EXT = True
except ImportError: # pragma: no cover
from yaml import (SafeLoader as YamlLoader, # type: ignore
from yaml import (SafeLoader as YamlLoader, # type: ignore[misc]
SafeDumper as YamlDumper)
YAML_C_EXT = False
@ -324,7 +324,7 @@ class FakeIOStream(io.TextIOBase):
def __init__(self, write_func: typing.Callable[[str], int]) -> None:
super().__init__()
self.write = write_func # type: ignore
self.write = write_func # type: ignore[assignment]
@contextlib.contextmanager
@ -338,16 +338,16 @@ def fake_io(write_func: typing.Callable[[str], int]) -> typing.Iterator[None]:
old_stderr = sys.stderr
fake_stderr = FakeIOStream(write_func)
fake_stdout = FakeIOStream(write_func)
sys.stderr = fake_stderr # type: ignore
sys.stdout = fake_stdout # type: ignore
sys.stderr = fake_stderr # type: ignore[assignment]
sys.stdout = fake_stdout # type: ignore[assignment]
try:
yield
finally:
# If the code we did run did change sys.stdout/sys.stderr, we leave it
# unchanged. Otherwise, we reset it.
if sys.stdout is fake_stdout: # type: ignore
if sys.stdout is fake_stdout: # type: ignore[comparison-overlap]
sys.stdout = old_stdout
if sys.stderr is fake_stderr: # type: ignore
if sys.stderr is fake_stderr: # type: ignore[comparison-overlap]
sys.stderr = old_stderr

View File

@ -43,7 +43,7 @@ from PyQt5.QtWidgets import QApplication
try:
from PyQt5.QtWebKit import qWebKitVersion
except ImportError: # pragma: no cover
qWebKitVersion = None # type: ignore # noqa: N816
qWebKitVersion = None # type: ignore[assignment] # noqa: N816
import qutebrowser
from qutebrowser.utils import log, utils, standarddir, usertypes, message
@ -54,7 +54,7 @@ from qutebrowser.config import config
try:
from qutebrowser.browser.webengine import webenginesettings
except ImportError: # pragma: no cover
webenginesettings = None # type: ignore
webenginesettings = None # type: ignore[assignment]
@attr.s
@ -373,7 +373,7 @@ def _chromium_version() -> str:
and https://chromereleases.googleblog.com/
"""
if webenginesettings is None:
return 'unavailable' # type: ignore
return 'unavailable' # type: ignore[unreachable]
if webenginesettings.parsed_user_agent is None:
webenginesettings.init_user_agent()

View File

@ -110,7 +110,7 @@ def _apply_platform_markers(config, item):
"https://bugreports.qt.io/browse/QTBUG-60673"),
('qtwebkit6021_xfail',
pytest.mark.xfail,
version.qWebKitVersion and # type: ignore
version.qWebKitVersion and # type: ignore[unreachable]
version.qWebKitVersion() == '602.1',
"Broken on WebKit 602.1")
]