Merge branch 'blyxxyz-style-in-lists'

This commit is contained in:
Florian Bruhin 2016-07-13 07:29:14 +02:00
commit e35dfe7aa3
32 changed files with 70 additions and 70 deletions

View File

@ -163,7 +163,7 @@ def _init_icon():
"""Initialize the icon of qutebrowser."""
icon = QIcon()
fallback_icon = QIcon()
for size in (16, 24, 32, 48, 64, 96, 128, 256, 512):
for size in [16, 24, 32, 48, 64, 96, 128, 256, 512]:
filename = ':/icons/qutebrowser-{}x{}.png'.format(size, size)
pixmap = QPixmap(filename)
qtutils.ensure_not_null(pixmap)
@ -275,7 +275,7 @@ def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
message.error('current', "Error in startup argument '{}': "
"{}".format(cmd, e))
else:
background = open_target in ('tab-bg', 'tab-bg-silent')
background = open_target in ['tab-bg', 'tab-bg-silent']
tabbed_browser.tabopen(url, background=background,
explicit=True)

View File

@ -201,7 +201,7 @@ class AbstractZoom(QObject):
@pyqtSlot(str, str)
def _on_config_changed(self, section, option):
if section == 'ui' and option in ('zoom-levels', 'default-zoom'):
if section == 'ui' and option in ['zoom-levels', 'default-zoom']:
if not self._default_zoom_changed:
factor = float(config.get('ui', 'default-zoom')) / 100
self._set_factor_internal(factor)

View File

@ -521,7 +521,7 @@ class CommandDispatcher:
background=bg, window=window)
elif where == 'up':
self._navigate_up(url, tab, bg, window)
elif where in ('decrement', 'increment'):
elif where in ['decrement', 'increment']:
self._navigate_incdec(url, where, tab, bg, window)
else: # pragma: no cover
raise ValueError("Got called with invalid value {} for "
@ -574,7 +574,7 @@ class CommandDispatcher:
"expected one of: {}".format(
direction, expected_values))
if direction in ('top', 'bottom'):
if direction in ['top', 'bottom']:
func()
else:
func(count=count)

View File

@ -608,7 +608,7 @@ class HintManager(QObject):
Return:
A QUrl with the absolute URL, or None.
"""
for attr in ('href', 'src'):
for attr in ['href', 'src']:
if attr in elem:
text = elem[attr].strip()
break
@ -677,8 +677,8 @@ class HintManager(QObject):
"""
if not isinstance(target, Target):
raise TypeError("Target {} is no Target member!".format(target))
if target in (Target.userscript, Target.spawn, Target.run,
Target.fill):
if target in [Target.userscript, Target.spawn, Target.run,
Target.fill]:
if not args:
raise cmdexc.CommandError(
"'args' is required with target userscript/spawn/run/"

View File

@ -345,7 +345,7 @@ class DownloadItem(QObject):
errmsg = ""
else:
errmsg = " - {}".format(self.error_msg)
if all(e is None for e in (perc, remaining, self.stats.total)):
if all(e is None for e in [perc, remaining, self.stats.total]):
return ('{index}: {name} [{speed:>10}|{down}]{errmsg}'.format(
index=self.index, name=self.basename, speed=speed,
down=down, errmsg=errmsg))
@ -451,7 +451,7 @@ class DownloadItem(QObject):
"""
# pylint: disable=bad-config-call
# WORKAROUND for https://bitbucket.org/logilab/astroid/issue/104/
assert position in ("fg", "bg")
assert position in ["fg", "bg"]
start = config.get('colors', 'downloads.{}.start'.format(position))
stop = config.get('colors', 'downloads.{}.stop'.format(position))
system = config.get('colors', 'downloads.{}.system'.format(position))

View File

@ -319,7 +319,7 @@ class _Downloader:
Args:
url: The file to download as QUrl.
"""
if url.scheme() not in {'http', 'https'}:
if url.scheme() not in ['http', 'https']:
return
# Prevent loading an asset twice
if url in self.loaded_urls:

View File

@ -83,7 +83,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
if elem.isNull():
raise IsNullError('{} is a null element!'.format(elem))
self._elem = elem
for name in ('addClass', 'appendInside', 'appendOutside',
for name in ['addClass', 'appendInside', 'appendOutside',
'attributeNS', 'classes', 'clone', 'document',
'encloseContentsWith', 'encloseWith',
'evaluateJavaScript', 'findAll', 'findFirst',
@ -97,7 +97,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
'setInnerXml', 'setOuterXml', 'setPlainText',
'setStyleProperty', 'styleProperty', 'tagName',
'takeFromDocument', 'toInnerXml', 'toOuterXml',
'toggleClass', 'webFrame', '__eq__', '__ne__'):
'toggleClass', 'webFrame', '__eq__', '__ne__']:
# We don't wrap some methods for which we have better alternatives:
# - Mapping access for attributeNames/hasAttribute/setAttribute/
# attribute/removeAttribute.
@ -194,7 +194,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
"""
self._check_vanished()
try:
return self['contenteditable'].lower() not in ('false', 'inherit')
return self['contenteditable'].lower() not in ['false', 'inherit']
except KeyError:
return False
@ -269,7 +269,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
return self._is_editable_input()
elif tag == 'textarea':
return self.is_writable()
elif tag in ('embed', 'applet'):
elif tag in ['embed', 'applet']:
# Flash/Java/...
return config.get('input', 'insert-mode-on-plugins') and not strict
elif tag == 'object':
@ -284,7 +284,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
self._check_vanished()
roles = ('combobox', 'textbox')
tag = self._elem.tagName().lower()
return self.get('role', None) in roles or tag in ('input', 'textarea')
return self.get('role', None) in roles or tag in ['input', 'textarea']
def remove_blank_target(self):
"""Remove target from link."""

View File

@ -300,7 +300,7 @@ class BrowserPage(QWebPage):
else:
reply.finished.connect(functools.partial(
self.display_content, reply, 'image/jpeg'))
elif (mimetype in {'application/pdf', 'application/x-pdf'} and
elif (mimetype in ['application/pdf', 'application/x-pdf'] and
config.get('content', 'enable-pdfjs')):
# Use pdf.js to display the page
self._show_pdfjs(reply)

View File

@ -159,14 +159,14 @@ class WebView(QWebView):
Args:
e: The QMouseEvent.
"""
if e.button() in (Qt.XButton1, Qt.LeftButton):
if e.button() in [Qt.XButton1, Qt.LeftButton]:
# Back button on mice which have it, or rocker gesture
if self.page().history().canGoBack():
self.back()
else:
message.error(self.win_id, "At beginning of history.",
immediately=True)
elif e.button() in (Qt.XButton2, Qt.RightButton):
elif e.button() in [Qt.XButton2, Qt.RightButton]:
# Forward button on mice which have it, or rocker gesture
if self.page().history().canGoForward():
self.forward()
@ -337,8 +337,8 @@ class WebView(QWebView):
@pyqtSlot(usertypes.KeyMode)
def on_mode_entered(self, mode):
"""Ignore attempts to focus the widget if in any status-input mode."""
if mode in (usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno):
if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
log.webview.debug("Ignoring focus because mode {} was "
"entered.".format(mode))
self.setFocusPolicy(Qt.NoFocus)
@ -346,8 +346,8 @@ class WebView(QWebView):
@pyqtSlot(usertypes.KeyMode)
def on_mode_left(self, mode):
"""Restore focus policy if status-input modes were left."""
if mode in (usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno):
if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
log.webview.debug("Restoring focus policy because mode {} was "
"left.".format(mode))
self.setFocusPolicy(Qt.WheelFocus)
@ -424,7 +424,7 @@ class WebView(QWebView):
is_rocker_gesture = (config.get('input', 'rocker-gestures') and
e.buttons() == Qt.LeftButton | Qt.RightButton)
if e.button() in (Qt.XButton1, Qt.XButton2) or is_rocker_gesture:
if e.button() in [Qt.XButton1, Qt.XButton2] or is_rocker_gesture:
self._mousepress_backforward(e)
super().mousePressEvent(e)
return

View File

@ -211,7 +211,7 @@ def _init_misc():
"""Initialize misc. config-related files."""
save_manager = objreg.get('save-manager')
state_config = ini.ReadWriteConfigParser(standarddir.data(), 'state')
for sect in ('general', 'geometry'):
for sect in ['general', 'geometry']:
try:
state_config.add_section(sect)
except configparser.DuplicateSectionError:
@ -242,7 +242,7 @@ def _init_misc():
path = os.devnull
else:
path = os.path.join(standarddir.config(), 'qsettings')
for fmt in (QSettings.NativeFormat, QSettings.IniFormat):
for fmt in [QSettings.NativeFormat, QSettings.IniFormat]:
QSettings.setPath(fmt, QSettings.UserScope, path)
@ -551,7 +551,7 @@ class ConfigManager(QObject):
"""Notify other objects the config has changed."""
log.config.debug("Config option changed: {} -> {}".format(
sectname, optname))
if sectname in ('colors', 'fonts'):
if sectname in ['colors', 'fonts']:
self.style_changed.emit(sectname, optname)
self.changed.emit(sectname, optname)

View File

@ -1342,7 +1342,7 @@ class AutoSearch(BaseType):
self._basic_validation(value)
if not value:
return
elif value.lower() in ('naive', 'dns'):
elif value.lower() in ['naive', 'dns']:
pass
else:
self.booltype.validate(value)
@ -1350,7 +1350,7 @@ class AutoSearch(BaseType):
def transform(self, value):
if not value:
return None
elif value.lower() in ('naive', 'dns'):
elif value.lower() in ['naive', 'dns']:
return value.lower()
elif self.booltype.transform(value):
# boolean true is an alias for naive matching

View File

@ -170,7 +170,7 @@ class ModeManager(QObject):
handled = parser.handle(event)
is_non_alnum = (
event.modifiers() not in (Qt.NoModifier, Qt.ShiftModifier) or
event.modifiers() not in [Qt.NoModifier, Qt.ShiftModifier] or
not event.text().strip())
if handled:

View File

@ -77,7 +77,7 @@ def get_window(via_ipc, force_window=False, force_tab=False,
win_id = window.win_id
window_to_raise = window
win_id = window.win_id
if open_target not in ('tab-silent', 'tab-bg-silent'):
if open_target not in ['tab-silent', 'tab-bg-silent']:
window_to_raise = window
if window_to_raise is not None:
window_to_raise.setWindowState(
@ -196,7 +196,7 @@ class MainWindow(QWidget):
@pyqtSlot(str, str)
def on_config_changed(self, section, option):
"""Resize the completion if related config options changed."""
if section == 'completion' and option in ('height', 'shrink'):
if section == 'completion' and option in ['height', 'shrink']:
self.resize_completion()
elif section == 'ui' and option == 'statusbar-padding':
self.resize_completion()

View File

@ -519,9 +519,9 @@ class StatusBar(QWidget):
window=self._win_id)
if keyparsers[mode].passthrough:
self._set_mode_text(mode.name)
if mode in (usertypes.KeyMode.insert,
if mode in [usertypes.KeyMode.insert,
usertypes.KeyMode.command,
usertypes.KeyMode.caret):
usertypes.KeyMode.caret]:
self.set_mode_active(mode, True)
@pyqtSlot(usertypes.KeyMode, usertypes.KeyMode)
@ -534,9 +534,9 @@ class StatusBar(QWidget):
self._set_mode_text(new_mode.name)
else:
self.txt.set_text(self.txt.Text.normal, '')
if old_mode in (usertypes.KeyMode.insert,
if old_mode in [usertypes.KeyMode.insert,
usertypes.KeyMode.command,
usertypes.KeyMode.caret):
usertypes.KeyMode.caret]:
self.set_mode_active(old_mode, False)
@config.change_filter('ui', 'message-timeout')

View File

@ -207,7 +207,7 @@ class Prompter(QObject):
def on_mode_left(self, mode):
"""Clear and reset input when the mode was left."""
prompt = objreg.get('prompt', scope='window', window=self._win_id)
if mode in (usertypes.KeyMode.prompt, usertypes.KeyMode.yesno):
if mode in [usertypes.KeyMode.prompt, usertypes.KeyMode.yesno]:
prompt.txt.setText('')
prompt.lineedit.clear()
prompt.lineedit.setEchoMode(QLineEdit.Normal)

View File

@ -120,10 +120,10 @@ class UrlText(textbase.TextBase):
status_str: The LoadStatus as string.
"""
status = usertypes.LoadStatus[status_str]
if status in (usertypes.LoadStatus.success,
if status in [usertypes.LoadStatus.success,
usertypes.LoadStatus.success_https,
usertypes.LoadStatus.error,
usertypes.LoadStatus.warn):
usertypes.LoadStatus.warn]:
self._normal_url_type = UrlType[status_str]
else:
self._normal_url_type = UrlType.normal

View File

@ -536,8 +536,8 @@ class TabbedBrowser(tabwidget.TabWidget):
@pyqtSlot(usertypes.KeyMode)
def on_mode_left(self, mode):
"""Give focus to current tab if command mode was left."""
if mode in (usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno):
if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
widget = self.currentWidget()
log.modes.debug("Left status-input mode, focusing {!r}".format(
widget))
@ -554,8 +554,8 @@ class TabbedBrowser(tabwidget.TabWidget):
tab = self.widget(idx)
log.modes.debug("Current tab changed, focusing {!r}".format(tab))
tab.setFocus()
for mode in (usertypes.KeyMode.hint, usertypes.KeyMode.insert,
usertypes.KeyMode.caret, usertypes.KeyMode.passthrough):
for mode in [usertypes.KeyMode.hint, usertypes.KeyMode.insert,
usertypes.KeyMode.caret, usertypes.KeyMode.passthrough]:
modeman.maybe_leave(self._win_id, mode, 'tab changed')
if self._now_focused is not None:
objreg.register('last-focused-tab', self._now_focused, update=True,

View File

@ -72,7 +72,7 @@ class TabWidget(QTabWidget):
position = config.get('tabs', 'position')
selection_behavior = config.get('tabs', 'select-on-remove')
self.setTabPosition(position)
tabbar.vertical = position in (QTabWidget.West, QTabWidget.East)
tabbar.vertical = position in [QTabWidget.West, QTabWidget.East]
tabbar.setSelectionBehaviorOnRemove(selection_behavior)
tabbar.refresh()
@ -542,11 +542,11 @@ class TabBarStyle(QCommonStyle):
style: The base/"parent" style.
"""
self._style = style
for method in ('drawComplexControl', 'drawItemPixmap',
for method in ['drawComplexControl', 'drawItemPixmap',
'generatedIconPixmap', 'hitTestComplexControl',
'itemPixmapRect', 'itemTextRect', 'polish', 'styleHint',
'subControlRect', 'unpolish', 'drawItemText',
'sizeFromContents', 'drawPrimitive'):
'sizeFromContents', 'drawPrimitive']:
target = getattr(self._style, method)
setattr(self, method, functools.partial(target))
super().__init__()

View File

@ -311,7 +311,7 @@ class SignalHandler(QObject):
# pylint: disable=import-error,no-member,useless-suppression
import fcntl
read_fd, write_fd = os.pipe()
for fd in (read_fd, write_fd):
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(read_fd, QSocketNotifier.Read,

View File

@ -175,7 +175,7 @@ def fix_harfbuzz(args):
else:
log.init.debug("Using old harfbuzz engine (auto)")
os.environ['QT_HARFBUZZ'] = 'old'
elif args.harfbuzz in ('old', 'new'):
elif args.harfbuzz in ['old', 'new']:
# forced harfbuzz variant
# FIXME looking at the Qt code, 'new' isn't a valid value, but leaving
# it empty and using new yields different behavior...

View File

@ -263,8 +263,8 @@ class IPCServer(QObject):
log.ipc.debug("We can read a line immediately.")
self.on_ready_read()
socket.error.connect(self.on_error)
if socket.error() not in (QLocalSocket.UnknownSocketError,
QLocalSocket.PeerClosedError):
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)
@ -311,7 +311,7 @@ class IPCServer(QObject):
self._handle_invalid_data()
return
for name in ('args', 'target_arg'):
for name in ['args', 'target_arg']:
if name not in json_data:
log.ipc.error("Missing {}: {}".format(name, decoded.strip()))
self._handle_invalid_data()
@ -493,8 +493,8 @@ def send_to_running_instance(socketname, command, target_arg, *,
socket.waitForDisconnected(CONNECT_TIMEOUT)
return True
else:
if socket.error() not in (QLocalSocket.ConnectionRefusedError,
QLocalSocket.ServerNotFoundError):
if socket.error() not in [QLocalSocket.ConnectionRefusedError,
QLocalSocket.ServerNotFoundError]:
raise SocketError("connecting to running instance", socket)
else:
log.ipc.debug("No existing instance present (error {})".format(

View File

@ -61,7 +61,7 @@ def _guess_autoescape(template_name):
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in ('html', 'htm', 'xml')
return ext in ['html', 'htm', 'xml']
def resource_url(path):

View File

@ -86,7 +86,7 @@ def _wrapper(win_id, method_name, text, *args, **kwargs):
win in objreg.window_registry.values() and
win.win_id == win_id)
if (config.get('ui', 'message-unfocused') or
method_name not in ('error', 'warning', 'info') or
method_name not in ['error', 'warning', 'info'] or
window_focused):
getattr(bridge, method_name)(text, *args, **kwargs)
else:

View File

@ -194,7 +194,7 @@ def _get_window_registry(window):
def _get_registry(scope, window=None, tab=None):
"""Get the correct registry for a given scope."""
if window is not None and scope not in ('window', 'tab'):
if window is not None and scope not in ['window', 'tab']:
raise TypeError("window is set with scope {}".format(scope))
if tab is not None and scope != 'tab':
raise TypeError("tab is set with scope {}".format(scope))

View File

@ -263,7 +263,7 @@ def is_url(urlstr):
# URLs with explicit schemes are always URLs
log.url.debug("Contains explicit scheme")
url = True
elif qurl_userinput.host() in ('localhost', '127.0.0.1', '::1'):
elif qurl_userinput.host() in ['localhost', '127.0.0.1', '::1']:
log.url.debug("Is localhost.")
url = True
elif is_special_url(qurl):

View File

@ -518,7 +518,7 @@ def normalize_keystr(keystr):
)
for (orig, repl) in replacements:
keystr = keystr.replace(orig, repl)
for mod in ('ctrl', 'meta', 'alt', 'shift'):
for mod in ['ctrl', 'meta', 'alt', 'shift']:
keystr = keystr.replace(mod + '-', mod + '+')
return keystr

View File

@ -167,7 +167,7 @@ def _os_info():
versioninfo = ''
else:
versioninfo = '.'.join(versioninfo)
osver = ', '.join([e for e in (release, versioninfo, machine) if e])
osver = ', '.join([e for e in [release, versioninfo, machine] if e])
else:
osver = '?'
lines.append('OS Version: {}'.format(osver))

View File

@ -197,7 +197,7 @@ class AsciiDoc:
for filename in files:
basename, ext = os.path.splitext(filename)
if (ext != '.asciidoc' or
basename in ('header', 'OpenSans-License')):
basename in ['header', 'OpenSans-License']):
continue
self._build_website_file(root, filename)

View File

@ -53,7 +53,7 @@ class ConfigChecker(checkers.BaseChecker):
if hasattr(node, 'func'):
infer = utils.safe_infer(node.func)
if infer and infer.root().name == 'qutebrowser.config.config':
if getattr(node.func, 'attrname', None) in ('get', 'set'):
if getattr(node.func, 'attrname', None) in ['get', 'set']:
self._check_config(node)
def _check_config(self, node):

View File

@ -42,7 +42,7 @@ class OpenEncodingChecker(checkers.BaseChecker):
if hasattr(node, 'func'):
infer = utils.safe_infer(node.func)
if infer and infer.root().name == '_io':
if getattr(node.func, 'name', None) in ('open', 'file'):
if getattr(node.func, 'name', None) in ['open', 'file']:
self._check_open_encoding(node)
def _check_open_encoding(self, node):

View File

@ -44,14 +44,14 @@ def whitelist_generator():
# pyPEG2 classes
for name, member in inspect.getmembers(rfc6266, inspect.isclass):
for attr in ('grammar', 'regex'):
for attr in ['grammar', 'regex']:
if hasattr(member, attr):
yield 'qutebrowser.browser.webkit.rfc6266.{}.{}'.format(name,
attr)
# PyQt properties
for attr in ('prompt_active', 'command_active', 'insert_active',
'caret_mode'):
for attr in ['prompt_active', 'command_active', 'insert_active',
'caret_mode']:
yield 'qutebrowser.mainwindow.statusbar.bar.StatusBar.' + attr
yield 'qutebrowser.mainwindow.statusbar.url.UrlText.urltype'
@ -89,16 +89,16 @@ def whitelist_generator():
# in NetworkManager.on_authentication_required
yield 'PyQt5.QtNetwork.QNetworkReply.netrc_used'
for attr in ('fileno', 'truncate', 'closed', 'readable'):
for attr in ['fileno', 'truncate', 'closed', 'readable']:
yield 'qutebrowser.utils.qtutils.PyQIODevice.' + attr
for attr in ('priority', 'visit_call'):
for attr in ['priority', 'visit_call']:
yield 'scripts.dev.pylint_checkers.config.' + attr
yield 'scripts.dev.pylint_checkers.modeline.process_module'
for attr in ('_get_default_metavar_for_optional',
'_get_default_metavar_for_positional', '_metavar_formatter'):
for attr in ['_get_default_metavar_for_optional',
'_get_default_metavar_for_positional', '_metavar_formatter']:
yield 'scripts.dev.src2asciidoc.UsageFormatter.' + attr

View File

@ -131,7 +131,7 @@ class TestStandardDir:
def test_linux_normal(self, monkeypatch, tmpdir, func, subdirs):
"""Test dirs with XDG_*_HOME not set."""
monkeypatch.setenv('HOME', str(tmpdir))
for var in ('DATA', 'CONFIG', 'CACHE'):
for var in ['DATA', 'CONFIG', 'CACHE']:
monkeypatch.delenv('XDG_{}_HOME'.format(var), raising=False)
assert func() == str(tmpdir.join(*subdirs))