Eschew the extraneous elses

https://www.youtube.com/watch?v=JVVMMULwR4s&t=289
This commit is contained in:
Florian Bruhin 2019-03-13 13:53:09 +01:00
parent 068168f351
commit 33463325f4
25 changed files with 51 additions and 71 deletions

View File

@ -479,7 +479,7 @@ class CommandDispatcher:
# Catch common cases before e.g. cloning tab
if not forward and not history.can_go_back():
raise cmdutils.CommandError("At beginning of history.")
elif forward and not history.can_go_forward():
if forward and not history.can_go_forward():
raise cmdutils.CommandError("At end of history.")
if tab or bg or window:

View File

@ -1105,8 +1105,7 @@ class DownloadModel(QAbstractListModel):
to_retry = [d for d in self if d.done and not d.successful]
if not to_retry:
raise cmdutils.CommandError("No failed downloads!")
else:
download = to_retry[0]
download = to_retry[0]
download.try_retry()
def can_clear(self):

View File

@ -956,10 +956,9 @@ class HintManager(QObject):
if keystring is None:
if self._context.to_follow is None:
raise cmdutils.CommandError("No hint to follow")
elif select:
if select:
raise cmdutils.CommandError("Can't use --select without hint.")
else:
keystring = self._context.to_follow
keystring = self._context.to_follow
elif keystring not in self._context.labels:
raise cmdutils.CommandError("No hint {}!".format(keystring))

View File

@ -142,7 +142,8 @@ class PACResolver:
config = [c.strip() for c in proxy_str.split(' ') if c]
if not config:
raise ParseProxyError("Empty proxy entry")
elif config[0] == "DIRECT":
if config[0] == "DIRECT":
if len(config) != 1:
raise ParseProxyError("Invalid number of parameters for " +
"DIRECT")

View File

@ -89,8 +89,7 @@ def serialize(items):
if current_idx is not None:
raise ValueError("Multiple active items ({} and {}) "
"found!".format(current_idx, i))
else:
current_idx = i
current_idx = i
if items:
if current_idx is None:

View File

@ -402,7 +402,8 @@ class Command:
if isinstance(typ, tuple):
raise TypeError("{}: Legacy tuple type annotation!".format(
self.name))
elif getattr(typ, '__origin__', None) is typing.Union or (
if getattr(typ, '__origin__', None) is typing.Union or (
# Older Python 3.5 patch versions
# pylint: disable=no-member,useless-suppression
hasattr(typing, 'UnionMeta') and

View File

@ -292,8 +292,7 @@ def debug_crash(typ: str = 'exception') -> None:
if typ == 'segfault':
os.kill(os.getpid(), signal.SIGSEGV)
raise Exception("Segfault failed (wat.)")
else:
raise Exception("Forced crash")
raise Exception("Forced crash")
@cmdutils.register(debug=True, maxsplit=0, no_cmd_split=True)

View File

@ -176,8 +176,7 @@ class BaseType:
(pytype == dict and value == {})):
if not self.none_ok:
raise configexc.ValidationError(value, "may not be null!")
else:
return
return
if (not isinstance(value, pytype) or
pytype is int and isinstance(value, bool)):
@ -365,9 +364,9 @@ class String(BaseType):
if minlen is not None and minlen < 1:
raise ValueError("minlen ({}) needs to be >= 1!".format(minlen))
elif maxlen is not None and maxlen < 1:
if maxlen is not None and maxlen < 1:
raise ValueError("maxlen ({}) needs to be >= 1!".format(maxlen))
elif maxlen is not None and minlen is not None and maxlen < minlen:
if maxlen is not None and minlen is not None and maxlen < minlen:
raise ValueError("minlen ({}) needs to be <= maxlen ({})!".format(
minlen, maxlen))
self.minlen = minlen
@ -1271,8 +1270,7 @@ class Regex(BaseType):
str(w.message).startswith('bad escape')):
raise configexc.ValidationError(
pattern, "must be a valid regex - " + str(w.message))
else:
warnings.warn(w.message)
warnings.warn(w.message)
return compiled
@ -1803,7 +1801,7 @@ class ConfirmQuit(FlagList):
raise configexc.ValidationError(
values, "List cannot contain never!")
# Always can't be set with other options
elif 'always' in values and len(values) > 1:
if 'always' in values and len(values) > 1:
raise configexc.ValidationError(
values, "List cannot contain always!")

View File

@ -207,8 +207,7 @@ class IPCServer(QObject):
if not ok:
if self._server.serverError() == QAbstractSocket.AddressInUseError:
raise AddressInUseError(self._server)
else:
raise ListenError(self._server)
raise ListenError(self._server)
if not utils.is_windows: # pragma: no cover
# If we use setSocketOptions on Unix with Qt < 5.4, we get a
# NameError while listening.
@ -452,19 +451,17 @@ def send_to_running_instance(socketname, command, target_arg, *, socket=None):
socket.waitForBytesWritten(WRITE_TIMEOUT)
if socket.error() != QLocalSocket.UnknownSocketError:
raise SocketError("writing to running instance", socket)
else:
socket.disconnectFromServer()
if socket.state() != QLocalSocket.UnconnectedState:
socket.waitForDisconnected(CONNECT_TIMEOUT)
return True
socket.disconnectFromServer()
if socket.state() != QLocalSocket.UnconnectedState:
socket.waitForDisconnected(CONNECT_TIMEOUT)
return True
else:
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(
socket.error()))
return False
log.ipc.debug("No existing instance present (error {})".format(
socket.error()))
return False
def display_error(exc, args):

View File

@ -136,8 +136,7 @@ class SessionManager(QObject):
path = os.path.join(self._base_path, name + '.yml')
if check_exists and not os.path.exists(path):
raise SessionNotFoundError(path)
else:
return path
return path
def exists(self, name):
"""Check if a named session exists."""

View File

@ -112,8 +112,7 @@ def raise_sqlite_error(msg, error):
if error_code in environmental_errors or qtbug_70506:
raise SqlEnvironmentError(msg, error)
else:
raise SqlBugError(msg, error)
raise SqlBugError(msg, error)
def init(db_path):

View File

@ -243,9 +243,8 @@ def log_capacity(capacity: int) -> None:
"""
if capacity < 0:
raise cmdutils.CommandError("Can't set a negative log capacity!")
else:
assert log.ram_handler is not None
log.ram_handler.change_log_capacity(capacity)
assert log.ram_handler is not None
log.ram_handler.change_log_capacity(capacity)
@cmdutils.register(debug=True)

View File

@ -304,6 +304,5 @@ def window_by_index(idx):
"""Get the Nth opened window object."""
if not window_registry:
raise NoWindow()
else:
key = sorted(window_registry)[idx]
return window_registry[key]
key = sorted(window_registry)[idx]
return window_registry[key]

View File

@ -131,13 +131,11 @@ def check_overflow(arg: int, ctype: str, fatal: bool = True) -> int:
if arg > maxval:
if fatal:
raise OverflowError(arg)
else:
return maxval
return maxval
elif arg < minval:
if fatal:
raise OverflowError(arg)
else:
return minval
return minval
else:
return arg

View File

@ -205,7 +205,7 @@ class UrlPattern:
if self._host.endswith('.*'):
# Special case to have a nicer error
raise ParseError("TLD wildcards are not implemented yet")
elif '*' in self._host:
if '*' in self._host:
# Only * or *.foo is allowed as host.
raise ParseError("Invalid host wildcard")

View File

@ -200,9 +200,8 @@ class NeighborList(collections.abc.Sequence):
"""Reset the position to the default."""
if self._default is _UNSET:
raise ValueError("No default set!")
else:
self._idx = self._items.index(self._default)
return self.curitem()
self._idx = self._items.index(self._default)
return self.curitem()
# The mode of a Question.

View File

@ -235,11 +235,11 @@ def check(fileobj, perfect_files):
"""Main entry point which parses/checks coverage.xml if applicable."""
if not utils.is_linux:
raise Skipped("on non-Linux system.")
elif '-k' in sys.argv[1:]:
if '-k' in sys.argv[1:]:
raise Skipped("because -k is given.")
elif '-m' in sys.argv[1:]:
if '-m' in sys.argv[1:]:
raise Skipped("because -m is given.")
elif '--lf' in sys.argv[1:]:
if '--lf' in sys.argv[1:]:
raise Skipped("because --lf is given.")
perfect_src_files = [e[1] for e in perfect_files]

View File

@ -499,7 +499,7 @@ def _format_block(filename, what, data):
if not found_start:
raise Exception("Marker '// QUTE_{}_START' not found in "
"'{}'!".format(what, filename))
elif not found_end:
if not found_end:
raise Exception("Marker '// QUTE_{}_END' not found in "
"'{}'!".format(what, filename))
except:

View File

@ -155,10 +155,10 @@ def run():
if browser not in query:
raise Error('Sorry, the selected browser: "{}" is not '
'supported.'.format(browser))
else:
history = extract(source, query[browser])
history = clean(history)
insert_qb(history, dest)
history = extract(source, query[browser])
history = clean(history)
insert_qb(history, dest)
def main():

View File

@ -121,8 +121,7 @@ def get_lib_path(executable, name, required=True):
if required:
raise Error("Could not import {} with {}: {}!".format(
name, executable, data))
else:
return None
return None
else:
raise ValueError("Unexpected output: {!r}".format(output))

View File

@ -824,9 +824,9 @@ class QuteProc(testprocess.Process):
message = self.wait_for_js('qute:*').message
if message.endswith('qute:no elems'):
raise ValueError('No element with {!r} found'.format(text))
elif message.endswith('qute:ambiguous elems'):
if message.endswith('qute:ambiguous elems'):
raise ValueError('Element with {!r} is not unique'.format(text))
elif not message.endswith('qute:okay'):
if not message.endswith('qute:okay'):
raise ValueError('Invalid response from qutebrowser: {}'
.format(message))

View File

@ -301,8 +301,7 @@ class FakeSignal:
def __call__(self):
if self._func is None:
raise TypeError("'FakeSignal' object is not callable")
else:
return self._func()
return self._func()
def connect(self, slot):
"""Connect the signal to a slot.
@ -530,10 +529,9 @@ class TabWidgetStub(QObject):
def indexOf(self, _tab):
if self.index_of is None:
raise ValueError("indexOf got called with index_of None!")
elif self.index_of is RuntimeError:
if self.index_of is RuntimeError:
raise RuntimeError
else:
return self.index_of
return self.index_of
def currentIndex(self):
if self.current_index is None:

View File

@ -190,8 +190,7 @@ class TestAdd:
def raise_error(url, replace=False):
if environmental:
raise sql.SqlEnvironmentError("Error message")
else:
raise sql.SqlBugError("Error message")
raise sql.SqlBugError("Error message")
if completion:
monkeypatch.setattr(web_history.completion, 'insert', raise_error)

View File

@ -65,8 +65,7 @@ def runner(request, runtime_tmpdir):
request.param is userscripts._POSIXUserscriptRunner):
pytest.skip("Requires a POSIX os")
raise utils.Unreachable
else:
return request.param()
return request.param()
def test_command(qtbot, py_proc, runner):

View File

@ -153,8 +153,7 @@ class QtObject:
"""Get the fake error, or raise AttributeError if set to None."""
if self._error is None:
raise AttributeError
else:
return self._error
return self._error
def isValid(self):
return self._valid