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 Sep 6, 2023
1 parent 911c420 commit f33f03b
Show file tree
Hide file tree
Showing 60 changed files with 173 additions and 149 deletions.
2 changes: 1 addition & 1 deletion hypothesis-python/docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
# General information about the project.
project = "Hypothesis"
author = "David R. MacIver"
copyright = f"2013-{datetime.datetime.utcnow().year}, {author}"
copyright = f"2013-{datetime.date.today().year}, {author}"

_d = {}
_version_file = root.joinpath("src", "hypothesis", "version.py")
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/scripts/validate_branch_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

for c, vs in sorted(checks.items()):
if len(vs) < 2:
v = list(vs)[0]
v = next(iter(vs))
assert v in (False, True)
if v:
always_true.append(c)
Expand Down
9 changes: 5 additions & 4 deletions hypothesis-python/src/_hypothesis_pytestplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def pytest_configure(config):
and Phase.explain not in settings.default.phases
):
name = f"{settings._current_profile}-with-explain-phase"
phases = settings.default.phases + (Phase.explain,)
phases = (*settings.default.phases, Phase.explain)
settings.register_profile(name, phases=phases)
settings.load_profile(name)

Expand Down Expand Up @@ -221,7 +221,7 @@ def raise_hypothesis_usage_error(msg):
("reproduce_example", "_hypothesis_internal_use_reproduce_failure"),
]:
if hasattr(item.obj, attribute):
from hypothesis.errors import InvalidArgument # noqa: F811
from hypothesis.errors import InvalidArgument

raise_hypothesis_usage_error(message % (name,))
yield
Expand Down Expand Up @@ -329,8 +329,9 @@ def pytest_runtest_makereport(item, call):
# If there's an HTML report, include our summary stats for each test
pytest_html = item.config.pluginmanager.getplugin("html")
if pytest_html is not None: # pragma: no cover
report.extra = getattr(report, "extra", []) + [
pytest_html.extras.text(stats, name="Hypothesis stats")
report.extra = [
*getattr(report, "extra", []),
pytest_html.extras.text(stats, name="Hypothesis stats"),
]

# This doesn't intrinsically have anything to do with the terminalreporter;
Expand Down
16 changes: 13 additions & 3 deletions hypothesis-python/src/hypothesis/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,17 @@
import os
import warnings
from enum import Enum, EnumMeta, IntEnum, unique
from typing import TYPE_CHECKING, Any, Collection, Dict, List, Optional, TypeVar, Union
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Collection,
Dict,
List,
Optional,
TypeVar,
Union,
)

import attr

Expand Down Expand Up @@ -128,7 +138,7 @@ class settings(metaclass=settingsMeta):
"""

__definitions_are_locked = False
_profiles: Dict[str, "settings"] = {}
_profiles: ClassVar[Dict[str, "settings"]] = {}
__module__ = "hypothesis"

def __getattr__(self, name):
Expand Down Expand Up @@ -706,7 +716,7 @@ def note_deprecation(
message: str, *, since: str, has_codemod: bool, stacklevel: int = 0
) -> None:
if since != "RELEASEDAY":
date = datetime.datetime.strptime(since, "%Y-%m-%d").date()
date = datetime.date.fromisoformat(since)
assert datetime.date(2021, 1, 1) <= date
if has_codemod:
message += (
Expand Down
5 changes: 3 additions & 2 deletions hypothesis-python/src/hypothesis/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def __call__(self, test: TestFunc) -> TestFunc:

def xfail(
self,
condition: bool = True,
condition: bool = True, # noqa: FBT002
*,
reason: str = "",
raises: Union[
Expand Down Expand Up @@ -868,7 +868,8 @@ def _execute_once_for_engine(self, data):
except (
HypothesisDeprecationWarning,
FailedHealthCheck,
) + skip_exceptions_to_reraise():
*skip_exceptions_to_reraise(),
):
# These are fatal errors or control exceptions that should stop the
# engine, so we re-raise them.
raise
Expand Down
8 changes: 4 additions & 4 deletions hypothesis-python/src/hypothesis/extra/_array_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def _hypothesis_parse_gufunc_signature(signature, *, all_checks=True):
)
names_in = {n.strip("?") for shp in input_shapes for n in shp}
names_out = {n.strip("?") for n in result_shape}
for shape in input_shapes + (result_shape,):
for shape in (*input_shapes, result_shape):
for name in shape:
try:
int(name.strip("?"))
Expand Down Expand Up @@ -408,7 +408,7 @@ def mutually_broadcastable_shapes(
)
check_type(str, signature, "signature")
parsed_signature = _hypothesis_parse_gufunc_signature(signature)
all_shapes = parsed_signature.input_shapes + (parsed_signature.result_shape,)
all_shapes = (*parsed_signature.input_shapes, parsed_signature.result_shape)
sig_dims = min(len(s) for s in all_shapes)
num_shapes = len(parsed_signature.input_shapes)

Expand Down Expand Up @@ -540,7 +540,7 @@ def _draw_core_dimensions(self, data):
# that we can do an accurate per-shape length cap.
dims = {}
shapes = []
for shape in self.signature.input_shapes + (self.signature.result_shape,):
for shape in (*self.signature.input_shapes, self.signature.result_shape):
shapes.append([])
for name in shape:
if name.isdigit():
Expand Down Expand Up @@ -614,7 +614,7 @@ def _draw_loop_dimensions(self, data, use=None):
if not any(use):
break

result_shape = result_shape[: max(map(len, [self.base_shape] + shapes))]
result_shape = result_shape[: max(map(len, [self.base_shape, *shapes]))]

assert len(shapes) == self.num_shapes
assert all(self.min_dims <= len(s) <= self.max_dims for s in shapes)
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@


RELEASED_VERSIONS = ("2021.12", "2022.12")
NOMINAL_VERSIONS = RELEASED_VERSIONS + ("draft",)
NOMINAL_VERSIONS = (*RELEASED_VERSIONS, "draft")
assert sorted(NOMINAL_VERSIONS) == list(NOMINAL_VERSIONS) # sanity check
NominalVersion = Literal["2021.12", "2022.12", "draft"]
assert get_args(NominalVersion) == NOMINAL_VERSIONS # sanity check
Expand All @@ -79,7 +79,7 @@
REAL_NAMES = ALL_INT_NAMES + FLOAT_NAMES
COMPLEX_NAMES = ("complex64", "complex128")
NUMERIC_NAMES = REAL_NAMES + COMPLEX_NAMES
DTYPE_NAMES = ("bool",) + NUMERIC_NAMES
DTYPE_NAMES = ("bool", *NUMERIC_NAMES)

DataType = TypeVar("DataType")

Expand Down
4 changes: 1 addition & 3 deletions hypothesis-python/src/hypothesis/extra/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,7 @@ def codemod(path):
help="force ghostwritten tests to be type-annotated (or not). "
"By default, match the code to test.",
)
def write(
func, writer, except_, style, annotate
): # noqa: D301 # \b disables autowrap
def write(func, writer, except_, style, annotate): # \b disables autowrap
"""`hypothesis write` writes property-based tests for you!
Type annotations are helpful but not required for our advanced introspection
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/extra/ghostwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,7 @@ def _make_test_body(
given_strategies = given_strategies or _get_strategies(
*funcs, pass_result_to_next_func=ghost in ("idempotent", "roundtrip")
)
reprs = [((k,) + _valid_syntax_repr(v)) for k, v in given_strategies.items()]
reprs = [((k, *_valid_syntax_repr(v))) for k, v in given_strategies.items()]
imports = imports.union(*(imp for _, imp, _ in reprs))
given_args = ", ".join(f"{k}={v}" for k, _, v in reprs)
given_args = _st_strategy_names(given_args)
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/internal/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def is_typed_named_tuple(cls):


def _hint_and_args(x):
return (x,) + get_args(x)
return (x, *get_args(x))


def get_type_hints(thing):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ class ConjectureRunner:
def __init__(
self,
test_function,
*,
settings=None,
random=None,
database_key=None,
Expand Down Expand Up @@ -979,7 +980,7 @@ def new_shrinker(self, example, predicate=None, allow_transition=None):
explain=Phase.explain in self.settings.phases,
)

def cached_test_function(self, buffer, error_on_discard=False, extend=0):
def cached_test_function(self, buffer, *, error_on_discard=False, extend=0):
"""Checks the tree to see if we've tested this buffer, and returns the
previous result if we have.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ class Shrinker:
"""

def derived_value(fn): # noqa: B902
def derived_value(fn):
"""It's useful during shrinking to have access to derived values of
the current shrink target.
Expand Down Expand Up @@ -308,7 +308,7 @@ def cached_calculations(self):

def cached(self, *keys):
def accept(f):
cache_key = (f.__name__,) + keys
cache_key = (f.__name__, *keys)
try:
return self.cached_calculations[cache_key]
except KeyError:
Expand Down Expand Up @@ -1553,7 +1553,7 @@ class ShrinkPass:
shrinks = attr.ib(default=0)
deletions = attr.ib(default=0)

def step(self, random_order=False):
def step(self, *, random_order=False):
tree = self.shrinker.shrink_pass_choice_trees[self]
if tree.exhausted:
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,15 @@ class Shrinker:
and simpler."""

def __init__(
self, initial, predicate, random, full=False, debug=False, name=None, **kwargs
self,
initial,
predicate,
random,
*,
full=False,
debug=False,
name=None,
**kwargs,
):
self.setup(**kwargs)
self.current = self.make_immutable(initial)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,11 @@ def incorporate_int(self, i):
def current_int(self):
return int_from_bytes(self.current)

def minimize_as_integer(self, full=False):
def minimize_as_integer(self):
Integer.shrink(
self.current_int,
lambda c: c == self.current_int or self.incorporate_int(c),
random=self.random,
full=full,
)

def partial_sort(self):
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/internal/escalation.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def escalate_hypothesis_internal_error():

filepath = None if tb is None else traceback.extract_tb(tb)[-1][0]
if is_hypothesis_file(filepath) and not isinstance(
e, (HypothesisException,) + HYPOTHESIS_CONTROL_EXCEPTIONS
e, (HypothesisException, *HYPOTHESIS_CONTROL_EXCEPTIONS)
):
raise

Expand Down
6 changes: 3 additions & 3 deletions hypothesis-python/src/hypothesis/internal/reflection.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ def is_first_param_referenced_in_function(f):
tree = ast.parse(textwrap.dedent(inspect.getsource(f)))
except Exception:
return True # Assume it's OK unless we know otherwise
name = list(get_signature(f).parameters)[0]
name = next(iter(get_signature(f).parameters))
return any(
isinstance(node, ast.Name)
and node.id == name
Expand Down Expand Up @@ -455,7 +455,7 @@ def nicerepr(v):
return re.sub(r"(\[)~([A-Z][a-z]*\])", r"\g<1>\g<2>", pretty(v))


def repr_call(f, args, kwargs, reorder=True):
def repr_call(f, args, kwargs, *, reorder=True):
# Note: for multi-line pretty-printing, see RepresentationPrinter.repr_call()
if reorder:
args, kwargs = convert_positional_arguments(f, args, kwargs)
Expand Down Expand Up @@ -523,7 +523,7 @@ def define_function_signature(name, docstring, signature):
for a in signature.parameters:
check_valid_identifier(a)

used_names = list(signature.parameters) + [name]
used_names = {*signature.parameters, name}

newsig = signature.replace(
parameters=[
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/provisional.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

# Remove special-use domain names from the list. For more discussion
# see https://github.com/HypothesisWorks/hypothesis/pull/3572
TOP_LEVEL_DOMAINS = ["COM"] + sorted((d for d in _tlds if d != "ARPA"), key=len)
TOP_LEVEL_DOMAINS = ["COM", *sorted((d for d in _tlds if d != "ARPA"), key=len)]


class DomainNameStrategy(st.SearchStrategy):
Expand Down
24 changes: 12 additions & 12 deletions hypothesis-python/src/hypothesis/stateful.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from typing import (
Any,
Callable,
ClassVar,
Dict,
Iterable,
List,
Expand Down Expand Up @@ -237,9 +238,9 @@ class RuleBasedStateMachine(metaclass=StateMachineMeta):
executed.
"""

_rules_per_class: Dict[type, List[classmethod]] = {}
_invariants_per_class: Dict[type, List[classmethod]] = {}
_initializers_per_class: Dict[type, List[classmethod]] = {}
_rules_per_class: ClassVar[Dict[type, List[classmethod]]] = {}
_invariants_per_class: ClassVar[Dict[type, List[classmethod]]] = {}
_initializers_per_class: ClassVar[Dict[type, List[classmethod]]] = {}

def __init__(self) -> None:
if not self.rules():
Expand Down Expand Up @@ -416,7 +417,7 @@ def __attrs_post_init__(self):
if isinstance(v, Bundle):
bundles.append(v)
consume = isinstance(v, BundleConsumer)
arguments[k] = BundleReferenceStrategy(v.name, consume)
arguments[k] = BundleReferenceStrategy(v.name, consume=consume)
else:
arguments[k] = v
self.bundles = tuple(bundles)
Expand All @@ -427,7 +428,7 @@ def __attrs_post_init__(self):


class BundleReferenceStrategy(SearchStrategy):
def __init__(self, name, consume=False):
def __init__(self, name: str, *, consume: bool = False):
self.name = name
self.consume = consume

Expand All @@ -447,10 +448,9 @@ def do_draw(self, data):


class Bundle(SearchStrategy[Ex]):
# TODO: deprecate passing `consume` as a positional argument
def __init__(self, name: str, consume: bool = False) -> None: # noqa # bool posarg
def __init__(self, name: str, *, consume: bool = False) -> None:
self.name = name
self.__reference_strategy = BundleReferenceStrategy(name, consume)
self.__reference_strategy = BundleReferenceStrategy(name, consume=consume)

def do_draw(self, data):
machine = data.draw(self_strategy)
Expand Down Expand Up @@ -524,7 +524,7 @@ def _convert_targets(targets, target):
if targets:
raise InvalidArgument(
"Passing both targets=%r and target=%r is redundant - pass "
"targets=%r instead." % (targets, target, tuple(targets) + (target,))
"targets=%r instead." % (targets, target, (*targets, target))
)
targets = (target,)

Expand Down Expand Up @@ -801,19 +801,19 @@ def precondition_wrapper(*args, **kwargs):
invariant = getattr(f, INVARIANT_MARKER, None)
if rule is not None:
assert invariant is None
new_rule = attr.evolve(rule, preconditions=rule.preconditions + (precond,))
new_rule = attr.evolve(rule, preconditions=(*rule.preconditions, precond))
setattr(precondition_wrapper, RULE_MARKER, new_rule)
elif invariant is not None:
assert rule is None
new_invariant = attr.evolve(
invariant, preconditions=invariant.preconditions + (precond,)
invariant, preconditions=(*invariant.preconditions, precond)
)
setattr(precondition_wrapper, INVARIANT_MARKER, new_invariant)
else:
setattr(
precondition_wrapper,
PRECONDITIONS_MARKER,
getattr(f, PRECONDITIONS_MARKER, ()) + (precond,),
(*getattr(f, PRECONDITIONS_MARKER, ()), precond),
)

return precondition_wrapper
Expand Down
Loading

0 comments on commit f33f03b

Please sign in to comment.