Skip to content

Commit

Permalink
Enable and fix more lint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD committed Aug 20, 2023
1 parent 590dde7 commit 6a169fb
Show file tree
Hide file tree
Showing 85 changed files with 339 additions and 298 deletions.
3 changes: 3 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
RELEASE_TYPE: patch

This patch enables and fixes many more of :pypi:`ruff`\ 's lint rules.
5 changes: 1 addition & 4 deletions hypothesis-python/examples/test_binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ def binary_search(ls, v):

def is_sorted(ls):
"""Is this list sorted?"""
for i in range(len(ls) - 1):
if ls[i] > ls[i + 1]:
return False
return True
return all(x <= y for x, y in zip(ls, ls[1:]))


Values = st.integers()
Expand Down
3 changes: 2 additions & 1 deletion hypothesis-python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ def local_file(name):
warnings.warn(
"This version of setuptools is too old to handle license_files "
"metadata key. For more info, see: "
"https://setuptools.pypa.io/en/latest/userguide/declarative_config.html#metadata"
"https://setuptools.pypa.io/en/latest/userguide/declarative_config.html#metadata",
stacklevel=1,
)


Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/_hypothesis_pytestplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def __call__(self, msg):
Note that the pytest developers no longer support your version either!
Disabling the Hypothesis pytest plugin...
"""
warnings.warn(PYTEST_TOO_OLD_MESSAGE % (pytest.__version__,))
warnings.warn(PYTEST_TOO_OLD_MESSAGE % (pytest.__version__,), stacklevel=1)

else:

Expand Down
1 change: 1 addition & 0 deletions hypothesis-python/src/hypothesis/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ def _define_setting(
cls,
name,
description,
*,
default,
options=None,
validator=None,
Expand Down
6 changes: 3 additions & 3 deletions hypothesis-python/src/hypothesis/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def reject() -> NoReturn:
raise UnsatisfiedAssumption()
raise UnsatisfiedAssumption


def assume(condition: object) -> bool:
Expand All @@ -35,7 +35,7 @@ def assume(condition: object) -> bool:
true, and let Hypothesis try to avoid similar examples in future.
"""
if not condition:
raise UnsatisfiedAssumption()
raise UnsatisfiedAssumption
return True


Expand All @@ -62,7 +62,7 @@ def current_build_context() -> "BuildContext":


class BuildContext:
def __init__(self, data, is_final=False, close_on_capture=True):
def __init__(self, data, *, is_final=False, close_on_capture=True):
assert isinstance(data, ConjectureData)
self.data = data
self.tasks = []
Expand Down
3 changes: 2 additions & 1 deletion hypothesis-python/src/hypothesis/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,7 @@ def __init__(self, test_runner, stuff, test, settings, random, wrapped_test):
def execute_once(
self,
data,
*,
print_example=False,
is_final=False,
expected_failure=None,
Expand Down Expand Up @@ -1493,7 +1494,7 @@ def find(
def test(v):
if condition(v):
last[:] = [v]
raise Found()
raise Found

if random is not None:
test = seed(random.getrandbits(64))(test)
Expand Down
41 changes: 21 additions & 20 deletions hypothesis-python/src/hypothesis/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ def _db_for_path(path=None):
path = storage_directory("examples")
if not _usable_dir(path): # pragma: no cover
warnings.warn(
HypothesisWarning(
"The database setting is not configured, and the default "
"location is unusable - falling back to an in-memory "
f"database for this session. {path=}"
)
"The database setting is not configured, and the default "
"location is unusable - falling back to an in-memory "
f"database for this session. {path=}",
HypothesisWarning,
stacklevel=3,
)
return InMemoryExampleDatabase()
if path in (None, ":memory:"):
Expand Down Expand Up @@ -488,11 +488,11 @@ def _prepare_for_io(self) -> None:
self._access_cache[keypath].add(PurePath(filename))
except BadZipFile:
warnings.warn(
HypothesisWarning(
"The downloaded artifact from GitHub is invalid. "
"This could be because the artifact was corrupted, "
"or because the artifact was not created by Hypothesis. "
)
"The downloaded artifact from GitHub is invalid. "
"This could be because the artifact was corrupted, "
"or because the artifact was not created by Hypothesis. ",
HypothesisWarning,
stacklevel=3,
)
self._disabled = True

Expand Down Expand Up @@ -534,18 +534,17 @@ def _initialize_db(self) -> None:
self._artifact = new_artifact
elif found_artifact is not None:
warnings.warn(
HypothesisWarning(
"Using an expired artifact as a fallback for the database: "
f"{found_artifact}"
)
"Using an expired artifact as a fallback for the database: "
f"{found_artifact}",
HypothesisWarning,
stacklevel=2,
)
self._artifact = found_artifact
else:
warnings.warn(
HypothesisWarning(
"Couldn't acquire a new or existing artifact. "
"Disabling database."
)
"Couldn't acquire a new or existing artifact. Disabling database.",
HypothesisWarning,
stacklevel=2,
)
self._disabled = True
return
Expand Down Expand Up @@ -587,7 +586,7 @@ def _get_bytes(self, url: str) -> Optional[bytes]: # pragma: no cover
)

if warning_message is not None:
warnings.warn(HypothesisWarning(warning_message))
warnings.warn(warning_message, HypothesisWarning, stacklevel=4)
return None

return response_bytes
Expand Down Expand Up @@ -624,7 +623,9 @@ def _fetch_artifact(self) -> Optional[Path]: # pragma: no cover
f.write(artifact_bytes)
except OSError:
warnings.warn(
HypothesisWarning("Could not save the latest artifact from GitHub. ")
"Could not save the latest artifact from GitHub. ",
HypothesisWarning,
stacklevel=3,
)
return None

Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/executors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


def default_executor(function): # pragma: nocover
raise NotImplementedError() # We don't actually use this any more
raise NotImplementedError # We don't actually use this any more


def setup_teardown_executor(setup, teardown):
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/_array_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def broadcastable_shapes(
# We are unsure if gufuncs allow frozen dimensions to be optional, but it's
# easy enough to support here - and so we will unless we learn otherwise.
_DIMENSION = r"\w+\??" # Note that \w permits digits too!
_SHAPE = rf"\((?:{_DIMENSION}(?:,{_DIMENSION})" + r"{0,31})?\)"
_SHAPE = rf"\((?:{_DIMENSION}(?:,{_DIMENSION}){{0,31}})?\)"
_ARGUMENT_LIST = f"{_SHAPE}(?:,{_SHAPE})*"
_SIGNATURE = rf"^{_ARGUMENT_LIST}->{_SHAPE}$"
_SIGNATURE_MULTIPLE_OUTPUT = rf"^{_ARGUMENT_LIST}->{_ARGUMENT_LIST}$"
Expand All @@ -286,7 +286,7 @@ class _GUfuncSig(NamedTuple):
result_shape: Shape


def _hypothesis_parse_gufunc_signature(signature, all_checks=True):
def _hypothesis_parse_gufunc_signature(signature, *, all_checks=True):
# Disable all_checks to better match the Numpy version, for testing
if not re.match(_SIGNATURE, signature):
if re.match(_SIGNATURE_MULTIPLE_OUTPUT, signature):
Expand Down
8 changes: 4 additions & 4 deletions hypothesis-python/src/hypothesis/extra/array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def warn_on_missing_dtypes(xp: Any, stubs: List[str]) -> None:
f"Array module {xp.__name__} does not have the following "
f"dtypes in its namespace: {f_stubs}",
HypothesisWarning,
stacklevel=3,
)


Expand Down Expand Up @@ -450,9 +451,7 @@ def do_draw(self, data):
else:
self.check_set_value(val, val_0d, self.elements_strategy)

result = self.xp.reshape(result, self.shape)

return result
return self.xp.reshape(result, self.shape)


def _arrays(
Expand Down Expand Up @@ -911,6 +910,7 @@ def make_strategies_namespace(
warn(
f"Could not determine whether module {xp.__name__} is an Array API library",
HypothesisWarning,
stacklevel=2,
)

try:
Expand Down Expand Up @@ -1013,7 +1013,7 @@ def floating_dtypes(
class StrategiesNamespace(SimpleNamespace):
def __init__(self, **kwargs):
for attr in ["name", "api_version"]:
if attr not in kwargs.keys():
if attr not in kwargs:
raise ValueError(f"'{attr}' kwarg required")
super().__init__(**kwargs)

Expand Down
5 changes: 2 additions & 3 deletions hypothesis-python/src/hypothesis/extra/ghostwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,10 +435,9 @@ def _guess_strategy_by_argname(name: str) -> st.SearchStrategy:
return st.nothing()

if (
name.endswith("_name")
name.endswith(("_name", "label"))
or (name.endswith("name") and "_" not in name)
or ("string" in name and "as" not in name)
or name.endswith("label")
or name in STRING_NAMES
):
return st.text()
Expand Down Expand Up @@ -747,7 +746,7 @@ def _get_module(obj):
raise RuntimeError(f"Could not find module for ufunc {obj.__name__} ({obj!r}")


def _get_qualname(obj, include_module=False):
def _get_qualname(obj, *, include_module=False):
# Replacing angle-brackets for objects defined in `.<locals>.`
qname = getattr(obj, "__qualname__", obj.__name__)
qname = qname.replace("<", "_").replace(">", "_").replace(" ", "")
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/internal/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def new_entry(self, key, value):
Returns the score to associate with the key.
"""
raise NotImplementedError()
raise NotImplementedError

def on_access(self, key, value, score):
"""Called every time a key that is already in the map is read or
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def choose(
node.children[i] = DeadNode
node.live_child_count -= 1
assert node.live_child_count == 0
raise DeadBranch()
raise DeadBranch

def finish(self) -> Sequence[int]:
"""Record the decisions made in the underlying tree and return
Expand Down
32 changes: 16 additions & 16 deletions hypothesis-python/src/hypothesis/internal/conjecture/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,27 +240,27 @@ def run(self) -> Any:
self.bytes_read = blocks.endpoints[self.block_count]
self.block(self.block_count)
self.block_count += 1
self.__pop(False)
self.__pop(discarded=False)
elif record >= START_EXAMPLE_RECORD:
self.__push(record - START_EXAMPLE_RECORD)
else:
assert record in (
STOP_EXAMPLE_DISCARD_RECORD,
STOP_EXAMPLE_NO_DISCARD_RECORD,
)
self.__pop(record == STOP_EXAMPLE_DISCARD_RECORD)
self.__pop(discarded=record == STOP_EXAMPLE_DISCARD_RECORD)
return self.finish()

def __push(self, label_index: int) -> None:
i = self.example_count
assert i < len(self.examples)
self.start_example(i, label_index)
self.start_example(i, label_index=label_index)
self.example_count += 1
self.example_stack.append(i)

def __pop(self, discarded: bool) -> None:
def __pop(self, *, discarded: bool) -> None:
i = self.example_stack.pop()
self.stop_example(i, discarded)
self.stop_example(i, discarded=discarded)

def begin(self) -> None:
"""Called at the beginning of the run to initialise any
Expand All @@ -276,7 +276,7 @@ def block(self, i: int) -> None:
"""Called with each ``draw_bits`` call, with ``i`` the index of the
corresponding block in ``self.examples.blocks``"""

def stop_example(self, i: int, discarded: bool) -> None:
def stop_example(self, i: int, *, discarded: bool) -> None:
"""Called at the end of each example, with ``i`` the
index of the example and ``discarded`` being ``True`` if ``stop_example``
was called with ``discard=True``."""
Expand Down Expand Up @@ -342,7 +342,7 @@ def start_example(self, label: int) -> None:
self.labels.append(label)
self.trail.append(START_EXAMPLE_RECORD + i)

def stop_example(self, discard: bool) -> None:
def stop_example(self, *, discard: bool) -> None:
if discard:
self.trail.append(STOP_EXAMPLE_DISCARD_RECORD)
else:
Expand Down Expand Up @@ -379,10 +379,10 @@ def begin(self):
self.starts = IntList.of_length(len(self.examples))
self.ends = IntList.of_length(len(self.examples))

def start_example(self, i: int, label_index: int) -> None:
def start_example(self, i: int, *, label_index: int) -> None:
self.starts[i] = self.bytes_read

def stop_example(self, i: int, discarded: bool) -> None:
def stop_example(self, i: int, *, discarded: bool) -> None:
self.ends[i] = self.bytes_read

def finish(self) -> Tuple[IntList, IntList]:
Expand All @@ -407,7 +407,7 @@ def begin(self) -> None:
def finish(self) -> FrozenSet[int]:
return frozenset(self.result)

def stop_example(self, i: int, discarded: bool) -> None:
def stop_example(self, i: int, *, discarded: bool) -> None:
if discarded:
self.result.add(i)

Expand All @@ -422,7 +422,7 @@ def block(self, i: int) -> None:
if not self.examples.blocks.trivial(i):
self.nontrivial[self.example_stack[-1]] = 1

def stop_example(self, i: int, discarded: bool) -> None:
def stop_example(self, i: int, *, discarded: bool) -> None:
if self.nontrivial[i]:
if self.example_stack:
self.nontrivial[self.example_stack[-1]] = 1
Expand All @@ -435,7 +435,7 @@ def finish(self) -> FrozenSet[int]:
trivial: FrozenSet[int] = calculated_example_property(_trivial)

class _parentage(ExampleProperty):
def stop_example(self, i: int, discarded: bool) -> None:
def stop_example(self, i: int, *, discarded: bool) -> None:
if i > 0:
self.result[i] = self.example_stack[-1]

Expand Down Expand Up @@ -746,7 +746,7 @@ def conclude_test(
Note that this is called after ``freeze`` has completed.
"""

def draw_bits(self, n_bits: int, forced: bool, value: int) -> None:
def draw_bits(self, n_bits: int, *, forced: bool, value: int) -> None:
"""Called when ``draw_bits`` is called on on the
observed ``ConjectureData``.
* ``n_bits`` is the number of bits drawn.
Expand Down Expand Up @@ -973,14 +973,14 @@ def start_example(self, label: int) -> None:
self.__example_record.start_example(label)
self.labels_for_structure_stack.append({label})

def stop_example(self, discard: bool = False) -> None:
def stop_example(self, *, discard: bool = False) -> None:
if self.frozen:
return
if discard:
self.has_discards = True
self.depth -= 1
assert self.depth >= -1
self.__example_record.stop_example(discard)
self.__example_record.stop_example(discard=discard)

labels_for_structure = self.labels_for_structure_stack.pop()

Expand Down Expand Up @@ -1082,7 +1082,7 @@ def draw_bits(self, n: int, *, forced: Optional[int] = None) -> int:
buf = bytes(buf)
result = int_from_bytes(buf)

self.observer.draw_bits(n, forced is not None, result)
self.observer.draw_bits(n, forced=forced is not None, value=result)
self.__example_record.draw_bits(n, forced)

initial = self.index
Expand Down
Loading

0 comments on commit 6a169fb

Please sign in to comment.