Options.get(): Fix inverted by_index check

The by_index branch of Options.get() raises KeyError for every integer
index, because the first isinstance guard is inverted: it fires for exactly
the keys the branch is supposed to handle, so the range check and the
lookup in the list of parsed keys below it are dead code. A non-integer key
with by_index set slips past the guard and falls through to the regular key
lookup instead. A previous make-check fallout commit flipped the original
type(key) != int test into a positive isinstance test, and a later mypy fix
then added redundant isinstance guards to the unreachable branches,
cementing the broken flow.

Invert the guard back to not isinstance(key, int), so that a non-integer
key raises KeyError, an in-range integer index returns the key stored at
that position in the option string, and an out-of-range index returns the
default or raises KeyError. Drop the redundant isinstance guards from the
now-reachable branches.

TODO: The bug actually made "make -C test/parse_opts run" fail, but since
jw-python's nightly CI doesn't run that, this has gone unnoticed. The test
now passes, but should be replaced with a better test (executed by "make
test", and pytest-based).

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-09-18 09:05:53 +02:00
commit b192207bbd
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -153,20 +153,19 @@ class Options: # export
def get(self, key: Any, default: Any = None, by_index: bool = False) -> Any:
if by_index:
if isinstance(key, int):
if not isinstance(key, int):
raise KeyError(
'Tried to get value from options string with ' +
'index {} of type "{}": {}'.format(key, type(key), str(self))
)
if isinstance(key, int) and key >= len(self.__data.pairs):
if key >= len(self.__data.pairs):
if default is not None:
return default
raise KeyError(
'Tried to get value from options string with ' +
'index {} of {}: {}'.format(key, len(self.__data.pairs), str(self))
)
if isinstance(key, int):
return self.__list[key]
return self.__list[key]
if key in self.__dict.keys():
return self.__dict[key]
if default is not None: