Change lists to tuples for immutable values

This commit is contained in:
Florian Bruhin 2014-06-06 17:12:54 +02:00
parent 03d754dd86
commit 2f1cd43f9c
21 changed files with 57 additions and 57 deletions

View File

@ -156,8 +156,8 @@ class Application(QApplication):
The argv list to be passed to Qt. The argv list to be passed to Qt.
""" """
argv = [sys.argv[0]] argv = [sys.argv[0]]
qt_args = ['style', 'stylesheet', 'widget-count', 'reverse', qt_args = ('style', 'stylesheet', 'widget-count', 'reverse',
'qmljsdebugger'] 'qmljsdebugger')
for argname in qt_args: for argname in qt_args:
val = getattr(namespace, 'qt_' + argname, None) val = getattr(namespace, 'qt_' + argname, None)
if val is None: if val is None:
@ -375,9 +375,9 @@ class Application(QApplication):
# config # config
self.config.style_changed.connect(style.invalidate_caches) self.config.style_changed.connect(style.invalidate_caches)
for obj in [tabs, completion, self.mainwindow, self.cmd_history, for obj in (tabs, completion, self.mainwindow, self.cmd_history,
websettings, kp['normal'], self.modeman, status, websettings, kp['normal'], self.modeman, status,
status.txt]: status.txt):
self.config.changed.connect(obj.on_config_changed) self.config.changed.connect(obj.on_config_changed)
# statusbar # statusbar

View File

@ -268,14 +268,14 @@ class HintManager(QObject):
pos = webelem.rect_on_view(elem).center() pos = webelem.rect_on_view(elem).center()
logger.debug("Clicking on '{}' at {}/{}".format(elem.toPlainText(), logger.debug("Clicking on '{}' at {}/{}".format(elem.toPlainText(),
pos.x(), pos.y())) pos.x(), pos.y()))
events = [ events = (
QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton, QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton,
Qt.NoModifier), Qt.NoModifier),
QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton, QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton,
Qt.NoButton, Qt.NoModifier), Qt.NoButton, Qt.NoModifier),
QMouseEvent(QEvent.MouseButtonRelease, pos, Qt.LeftButton, QMouseEvent(QEvent.MouseButtonRelease, pos, Qt.LeftButton,
Qt.NoButton, Qt.NoModifier), Qt.NoButton, Qt.NoModifier),
] )
for evt in events: for evt in events:
self.mouse_event.emit(evt) self.mouse_event.emit(evt)
@ -330,7 +330,7 @@ class HintManager(QObject):
# First check for <link rel="prev(ious)|next"> # First check for <link rel="prev(ious)|next">
elems = frame.findAllElements( elems = frame.findAllElements(
webelem.SELECTORS[webelem.Group.prevnext_rel]) webelem.SELECTORS[webelem.Group.prevnext_rel])
rel_values = ['prev', 'previous'] if prev else ['next'] rel_values = ('prev', 'previous') if prev else ('next')
for e in elems: for e in elems:
if e.attribute('rel') in rel_values: if e.attribute('rel') in rel_values:
return e return e

View File

@ -347,7 +347,7 @@ class ConfigManager(QObject):
except KeyError: except KeyError:
raise NoOptionError(optname, sectname) raise NoOptionError(optname, sectname)
else: else:
if sectname in ['colors', 'fonts']: if sectname in ('colors', 'fonts'):
self.style_changed.emit(sectname, optname) self.style_changed.emit(sectname, optname)
self.changed.emit(sectname, optname) self.changed.emit(sectname, optname)

View File

@ -459,7 +459,7 @@ class Color(CssColor):
typestr = 'color' typestr = 'color'
_GRADIENTS = ['qlineargradient', 'qradialgradient', 'qconicalgradient'] _GRADIENTS = ('qlineargradient', 'qradialgradient', 'qconicalgradient')
def validate(self, value): def validate(self, value):
if any([value.startswith(start) for start in Color._GRADIENTS]): if any([value.startswith(start) for start in Color._GRADIENTS]):
@ -775,13 +775,13 @@ class AutoSearch(BaseType):
('false', "Never search automatically.")) ('false', "Never search automatically."))
def validate(self, value): def validate(self, value):
if value.lower() in ['naive', 'dns']: if value.lower() in ('naive', 'dns'):
pass pass
else: else:
Bool.validate(self, value) Bool.validate(self, value)
def transform(self, value): def transform(self, value):
if value.lower() in ['naive', 'dns']: if value.lower() in ('naive', 'dns'):
return value.lower() return value.lower()
elif super().transform(value): elif super().transform(value):
# boolean true is an alias for naive matching # boolean true is an alias for naive matching

View File

@ -92,15 +92,15 @@ class BaseKeyParser(QObject):
Return: Return:
The normalized keystring. The normalized keystring.
""" """
replacements = [ replacements = (
('Control', 'Ctrl'), ('Control', 'Ctrl'),
('Windows', 'Meta'), ('Windows', 'Meta'),
('Mod1', 'Alt'), ('Mod1', 'Alt'),
('Mod4', 'Meta'), ('Mod4', 'Meta'),
] )
for (orig, repl) in replacements: for (orig, repl) in replacements:
keystr = keystr.replace(orig, repl) keystr = keystr.replace(orig, repl)
for mod in ['Ctrl', 'Meta', 'Alt', 'Shift']: for mod in ('Ctrl', 'Meta', 'Alt', 'Shift'):
keystr = keystr.replace(mod + '-', mod + '+') keystr = keystr.replace(mod + '-', mod + '+')
keystr = QKeySequence(keystr).toString() keystr = QKeySequence(keystr).toString()
return keystr return keystr
@ -122,7 +122,7 @@ class BaseKeyParser(QObject):
Qt.MetaModifier: 'Meta', Qt.MetaModifier: 'Meta',
Qt.ShiftModifier: 'Shift' Qt.ShiftModifier: 'Shift'
} }
if e.key() in [Qt.Key_Control, Qt.Key_Alt, Qt.Key_Shift, Qt.Key_Meta]: if e.key() in (Qt.Key_Control, Qt.Key_Alt, Qt.Key_Shift, Qt.Key_Meta):
# Only modifier pressed # Only modifier pressed
return False return False
mod = e.modifiers() mod = e.modifiers()

View File

@ -1,4 +1,4 @@
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>:
# #
# This file is part of qutebrowser. # This file is part of qutebrowser.
# #
@ -63,7 +63,7 @@ class ConfigStub:
Return: Return:
The section as dict. The section as dict.
""" """
if name not in ['test', 'test2']: if name not in ('test', 'test2'):
raise ValueError("section called with section '{}'!".format(name)) raise ValueError("section called with section '{}'!".format(name))
return self.DATA[name] return self.DATA[name]
@ -91,14 +91,14 @@ class NormalizeTests(TestCase):
def test_normalize(self): def test_normalize(self):
"""Test normalize with some strings.""" """Test normalize with some strings."""
STRINGS = [ STRINGS = (
('Control+x', 'Ctrl+X'), ('Control+x', 'Ctrl+X'),
('Windows+x', 'Meta+X'), ('Windows+x', 'Meta+X'),
('Mod1+x', 'Alt+X'), ('Mod1+x', 'Alt+X'),
('Mod4+x', 'Meta+X'), ('Mod4+x', 'Meta+X'),
('Control--', 'Ctrl+-'), ('Control--', 'Ctrl+-'),
('Windows++', 'Meta++'), ('Windows++', 'Meta++'),
] )
for orig, repl in STRINGS: for orig, repl in STRINGS:
self.assertEqual(self.kp._normalize_keystr(orig), repl, orig) self.assertEqual(self.kp._normalize_keystr(orig), repl, orig)

View File

@ -204,19 +204,19 @@ class ShellEscapeTests(TestCase):
platform: The saved sys.platform value. platform: The saved sys.platform value.
""" """
TEXTS_LINUX = [ TEXTS_LINUX = (
('', "''"), ('', "''"),
('foo%bar+baz', 'foo%bar+baz'), ('foo%bar+baz', 'foo%bar+baz'),
('foo$bar', "'foo$bar'"), ('foo$bar', "'foo$bar'"),
("$'b", """'$'"'"'b'"""), ("$'b", """'$'"'"'b'"""),
] )
TEXTS_WINDOWS = [ TEXTS_WINDOWS = (
('', '""'), ('', '""'),
('foo*bar?baz', 'foo*bar?baz'), ('foo*bar?baz', 'foo*bar?baz'),
("a&b|c^d<e>f%", "a^&b^|c^^d^<e^>f^%"), ("a&b|c^d<e>f%", "a^&b^|c^^d^<e^>f^%"),
('foo"bar', 'foo"""bar'), ('foo"bar', 'foo"""bar'),
] )
def setUp(self): def setUp(self):
self.platform = sys.platform self.platform = sys.platform

View File

@ -106,16 +106,16 @@ class SpecialURLTests(TestCase):
NORMAL_URLS: URLs which are not special. NORMAL_URLS: URLs which are not special.
""" """
SPECIAL_URLS = [ SPECIAL_URLS = (
'file:///tmp/foo', 'file:///tmp/foo',
'about:blank', 'about:blank',
'qute:version' 'qute:version'
] )
NORMAL_URLS = [ NORMAL_URLS = (
'http://www.qutebrowser.org/', 'http://www.qutebrowser.org/',
'www.qutebrowser.org' 'www.qutebrowser.org'
] )
def test_special_urls(self): def test_special_urls(self):
"""Test special URLs.""" """Test special URLs."""
@ -176,18 +176,18 @@ class IsUrlNaiveTests(TestCase):
NOT_URLS: A list of strings which aren't URLs. NOT_URLS: A list of strings which aren't URLs.
""" """
URLS = [ URLS = (
'http://foobar', 'http://foobar',
'localhost:8080', 'localhost:8080',
'qutebrowser.org', 'qutebrowser.org',
] )
NOT_URLS = [ NOT_URLS = (
'foo bar', 'foo bar',
'localhost test', 'localhost test',
'another . test', 'another . test',
'foo', 'foo',
] )
def test_urls(self): def test_urls(self):
"""Test things which are URLs.""" """Test things which are URLs."""

View File

@ -290,12 +290,12 @@ class JavascriptEscapeTests(TestCase):
STRINGS: A list of (input, output) tuples. STRINGS: A list of (input, output) tuples.
""" """
STRINGS = [ STRINGS = (
('foo\\bar', r'foo\\bar'), ('foo\\bar', r'foo\\bar'),
('foo\nbar', r'foo\nbar'), ('foo\nbar', r'foo\nbar'),
("foo'bar", r"foo\'bar"), ("foo'bar", r"foo\'bar"),
('foo"bar', r'foo\"bar'), ('foo"bar', r'foo\"bar'),
] )
def test_fake_escape(self): def test_fake_escape(self):
for before, after in self.STRINGS: for before, after in self.STRINGS:

View File

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

View File

@ -177,9 +177,9 @@ def qt_message_handler(msg_type, context, msg):
# Change levels of some well-known messages to debug so they don't get # Change levels of some well-known messages to debug so they don't get
# shown to the user. # shown to the user.
# suppressed_msgs is a list of regexes matching the message texts to hide. # suppressed_msgs is a list of regexes matching the message texts to hide.
suppressed_msgs = ["libpng warning: iCCP: Not recognizing known sRGB " suppressed_msgs = ("libpng warning: iCCP: Not recognizing known sRGB "
"profile that has been edited", "profile that has been edited",
"OpenType support missing for script [0-9]*"] "OpenType support missing for script [0-9]*")
if any(re.match(pattern, msg.strip()) for pattern in suppressed_msgs): if any(re.match(pattern, msg.strip()) for pattern in suppressed_msgs):
level = logging.DEBUG level = logging.DEBUG
else: else:

View File

@ -50,12 +50,12 @@ class Style(QCommonStyle):
style: The base/"parent" style. style: The base/"parent" style.
""" """
self._style = style self._style = style
for method in ['drawComplexControl', 'drawControl', 'drawItemPixmap', for method in ('drawComplexControl', 'drawControl', 'drawItemPixmap',
'drawItemText', 'generatedIconPixmap', 'drawItemText', 'generatedIconPixmap',
'hitTestComplexControl', 'itemPixmapRect', 'hitTestComplexControl', 'itemPixmapRect',
'itemTextRect', 'pixelMetric', 'polish', 'styleHint', 'itemTextRect', 'pixelMetric', 'polish', 'styleHint',
'subControlRect', 'subElementRect', 'unpolish', 'subControlRect', 'subElementRect', 'unpolish',
'sizeFromContents']: 'sizeFromContents'):
target = getattr(self._style, method) target = getattr(self._style, method)
setattr(self, method, functools.partial(target)) setattr(self, method, functools.partial(target))
super().__init__() super().__init__()

View File

@ -73,7 +73,7 @@ def _is_url_naive(url):
Return: Return:
True if the URL really is a URL, False otherwise. True if the URL really is a URL, False otherwise.
""" """
protocols = ['http', 'https'] protocols = ('http', 'https')
u = qurl(url) u = qurl(url)
urlstr = urlstring(url) urlstr = urlstring(url)
if isinstance(url, QUrl): if isinstance(url, QUrl):
@ -159,7 +159,7 @@ def fuzzy_url(url):
def is_special_url(url): def is_special_url(url):
"""Return True if url is an about:... or other special URL.""" """Return True if url is an about:... or other special URL."""
special_schemes = ['about', 'qute', 'file'] special_schemes = ('about', 'qute', 'file')
return qurl(url).scheme() in special_schemes return qurl(url).scheme() in special_schemes

View File

@ -128,12 +128,12 @@ def javascript_escape(text):
""" """
# This is a list of tuples because order matters, and using OrderedDict # This is a list of tuples because order matters, and using OrderedDict
# makes no sense because we don't actually need dict-like properties. # makes no sense because we don't actually need dict-like properties.
replacements = [ replacements = (
('\\', r'\\'), # First escape all literal \ signs as \\. ('\\', r'\\'), # First escape all literal \ signs as \\.
("'", r"\'"), # Then escape ' and " as \' and \". ("'", r"\'"), # Then escape ' and " as \' and \".
('"', r'\"'), # (note it won't hurt when we escape the wrong one). ('"', r'\"'), # (note it won't hurt when we escape the wrong one).
('\n', r'\n'), # We also need to escape newlines for some reason. ('\n', r'\n'), # We also need to escape newlines for some reason.
] )
for orig, repl in replacements: for orig, repl in replacements:
text = text.replace(orig, repl) text = text.replace(orig, repl)
return text return text

View File

@ -83,7 +83,7 @@ class CompletionView(QTreeView):
{color[completion.item.selected.fg]} {color[completion.item.selected.fg]}
}} }}
""" """
COLUMN_WIDTHS = [20, 70, 10] COLUMN_WIDTHS = (20, 70, 10)
# FIXME style scrollbar # FIXME style scrollbar

View File

@ -89,7 +89,7 @@ class MainWindow(QWidget):
@pyqtSlot(str, str) @pyqtSlot(str, str)
def on_config_changed(self, section, option): def on_config_changed(self, section, option):
"""Resize completion if config changed.""" """Resize completion if config changed."""
if section == 'completion' and option in ['height', 'shrink']: if section == 'completion' and option in ('height', 'shrink'):
self.resize_completion() self.resize_completion()
@pyqtSlot() @pyqtSlot()

View File

@ -71,7 +71,7 @@ class Prompt(QWidget):
cancelled: Emitted when the mode was forcibly left by the user cancelled: Emitted when the mode was forcibly left by the user
without answering the question. without answering the question.
""" """
if mode in ['prompt', 'yesno']: if mode in ('prompt', 'yesno'):
self._txt.setText('') self._txt.setText('')
self._input.clear() self._input.clear()
self._input.setEchoMode(QLineEdit.Normal) self._input.setEchoMode(QLineEdit.Normal)

View File

@ -147,7 +147,7 @@ class Url(TextBase):
Args: Args:
status: The LoadStatus as string. status: The LoadStatus as string.
""" """
if status in ['success', 'error', 'warn']: if status in ('success', 'error', 'warn'):
self.normal_url_type = status self.normal_url_type = status
else: else:
self.normal_url_type = 'normal' self.normal_url_type = 'normal'
@ -186,7 +186,7 @@ class Url(TextBase):
self.hover_url = None self.hover_url = None
self.normal_url = tab.url_text self.normal_url = tab.url_text
status = LoadStatus[tab.load_status] status = LoadStatus[tab.load_status]
if status in ['success', 'error', 'warn']: if status in ('success', 'error', 'warn'):
self.normal_url_type = status self.normal_url_type = status
else: else:
self.normal_url_type = 'normal' self.normal_url_type = 'normal'

View File

@ -191,7 +191,7 @@ class WebView(QWebView):
return False return False
elem = hitresult.element() elem = hitresult.element()
tag = elem.tagName().lower() tag = elem.tagName().lower()
if tag in ['embed', 'applet', 'select']: if tag in ('embed', 'applet', 'select'):
# Flash/Java/... # Flash/Java/...
return True return True
if tag == 'object': if tag == 'object':
@ -401,7 +401,7 @@ class WebView(QWebView):
@pyqtSlot(str, str) @pyqtSlot(str, str)
def on_config_changed(self, section, option): def on_config_changed(self, section, option):
"""Update tab config when config was changed.""" """Update tab config when config was changed."""
if section == 'ui' and option in ['zoom-levels', 'default-zoom']: if section == 'ui' and option in ('zoom-levels', 'default-zoom'):
self._init_neighborlist() self._init_neighborlist()
@pyqtSlot('QMouseEvent') @pyqtSlot('QMouseEvent')
@ -413,7 +413,7 @@ class WebView(QWebView):
@pyqtSlot() @pyqtSlot()
def on_load_started(self): def on_load_started(self):
"""Leave insert/hint mode and set vars when a new page is loading.""" """Leave insert/hint mode and set vars when a new page is loading."""
for mode in ['insert', 'hint']: for mode in ('insert', 'hint'):
modeman.maybe_leave(mode, 'load started') modeman.maybe_leave(mode, 'load started')
self.progress = 0 self.progress = 0
self._has_ssl_errors = False self._has_ssl_errors = False
@ -525,7 +525,7 @@ class WebView(QWebView):
Return: Return:
The superclass return value. The superclass return value.
""" """
if e.button() in [Qt.XButton1, Qt.XButton2]: if e.button() in (Qt.XButton1, Qt.XButton2):
self._mousepress_backforward(e) self._mousepress_backforward(e)
return super().mousePressEvent(e) return super().mousePressEvent(e)
self._mousepress_insertmode(e) self._mousepress_insertmode(e)

View File

@ -26,10 +26,10 @@ import shutil
from fnmatch import fnmatch from fnmatch import fnmatch
recursive_lint = ['__pycache__', '*.pyc'] recursive_lint = ('__pycache__', '*.pyc')
lint = ['build', 'dist', 'pkg/pkg', 'pkg/qutebrowser-*.pkg.tar.xz', 'pkg/src', lint = ('build', 'dist', 'pkg/pkg', 'pkg/qutebrowser-*.pkg.tar.xz', 'pkg/src',
'pkg/qutebrowser', 'qutebrowser.egg-info', 'setuptools-*.egg', 'pkg/qutebrowser', 'qutebrowser.egg-info', 'setuptools-*.egg',
'setuptools-*.zip'] 'setuptools-*.zip')
def remove(path): def remove(path):

View File

@ -262,21 +262,21 @@ for trg in options['targets']:
print("==================== {} ====================".format(trg)) print("==================== {} ====================".format(trg))
if do_check_257: if do_check_257:
check_pep257(trg, _get_args('pep257')) check_pep257(trg, _get_args('pep257'))
for chk in ['pylint', 'flake8']: for chk in ('pylint', 'flake8'):
# FIXME what the hell is the flake8 exit status? # FIXME what the hell is the flake8 exit status?
run(chk, trg, _get_args(chk)) run(chk, trg, _get_args(chk))
check_line(trg, ) check_line(trg, )
if '--setup' in argv: if '--setup' in argv:
print("==================== Setup checks ====================") print("==================== Setup checks ====================")
for chk in ['pyroma', 'check-manifest']: for chk in ('pyroma', 'check-manifest'):
run(chk, args=_get_args(chk)) run(chk, args=_get_args(chk))
print("Exit status values:") print("Exit status values:")
for (k, v) in status.items(): for (k, v) in status.items():
print(' {} - {}'.format(k, v)) print(' {} - {}'.format(k, v))
if all(val in [True, 0] for val in status): if all(val in (True, 0) for val in status):
sys.exit(0) sys.exit(0)
else: else:
sys.exit(1) sys.exit(1)