Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pylint fixes #3499

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 2 additions & 4 deletions HypothesisWorks.github.io/scratch/voting.py
Expand Up @@ -29,8 +29,7 @@ def plurality_winner(election):
winners = [c for c, v in counts.items() if v == winning_score]
if len(winners) > 1:
return None
else:
return winners[0]
return winners[0]


def irv_winner(election):
Expand All @@ -46,8 +45,7 @@ def irv_winner(election):
candidates = [c for c in candidates if scores[c] > losing_score]
if not candidates:
return None
else:
return candidates[0]
return candidates[0]


def differing_without_ties(election):
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/scripts/validate_branch_check.py
Expand Up @@ -13,7 +13,7 @@
from collections import defaultdict

if __name__ == "__main__":
with open("branch-check") as i:
with open("branch-check", encoding="utf-8") as i:
data = [json.loads(l) for l in i]

checks = defaultdict(set)
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/setup.py
Expand Up @@ -45,7 +45,7 @@ def local_file(name):
# Assignment to placate pyflakes. The actual version is from the exec that follows.
__version__ = None

with open(local_file("src/hypothesis/version.py")) as o:
with open(local_file("src/hypothesis/version.py"), encoding="utf-8") as o:
exec(o.read())

assert __version__ is not None
Expand Down Expand Up @@ -133,7 +133,7 @@ def local_file(name):
"pytest11": ["hypothesispytest = _hypothesis_pytestplugin"],
"console_scripts": ["hypothesis = hypothesis.extra.cli:main"],
},
long_description=open(README).read(),
long_description=open(README, encoding="utf-8").read(),
long_description_content_type="text/x-rst",
keywords="python testing fuzzing property-based-testing",
)
5 changes: 2 additions & 3 deletions hypothesis-python/src/_hypothesis_pytestplugin.py
Expand Up @@ -285,11 +285,10 @@ def _stash_get(config, key, default):
if hasattr(config, "stash"):
# pytest 7
return config.stash.get(key, default)
elif hasattr(config, "_store"):
if hasattr(config, "_store"):
# pytest 5.4
return config._store.get(key, default)
else:
return getattr(config, key, default)
return getattr(config, key, default)

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
Expand Down
39 changes: 18 additions & 21 deletions hypothesis-python/src/hypothesis/_settings.py
Expand Up @@ -52,19 +52,18 @@ def __init__(self, name, show_default):
def __get__(self, obj, type=None):
if obj is None:
return self
else:
try:
result = obj.__dict__[self.name]
# This is a gross hack, but it preserves the old behaviour that
# you can change the storage directory and it will be reflected
# in the default database.
if self.name == "database" and result is not_set:
from hypothesis.database import ExampleDatabase

result = ExampleDatabase(not_set)
return result
except KeyError:
raise AttributeError(self.name) from None
try:
result = obj.__dict__[self.name]
# This is a gross hack, but it preserves the old behaviour that
# you can change the storage directory and it will be reflected
# in the default database.
if self.name == "database" and result is not_set:
from hypothesis.database import ExampleDatabase

result = ExampleDatabase(not_set)
return result
except KeyError:
raise AttributeError(self.name) from None

def __set__(self, obj, value):
obj.__dict__[self.name] = value
Expand Down Expand Up @@ -109,7 +108,7 @@ def __setattr__(cls, name, value):
"Cannot assign to the property settings.default - "
"consider using settings.load_profile instead."
)
elif not (isinstance(value, settingsProperty) or name.startswith("_")):
if not (isinstance(value, settingsProperty) or name.startswith("_")):
raise AttributeError(
f"Cannot assign hypothesis.settings.{name}={value!r} - the settings "
"class is immutable. You can change the global default "
Expand All @@ -134,8 +133,7 @@ class settings(metaclass=settingsMeta):
def __getattr__(self, name):
if name in all_settings:
return all_settings[name].default
else:
raise AttributeError(f"settings has no attribute {name}")
raise AttributeError(f"settings has no attribute {name}")

def __init__(
self,
Expand Down Expand Up @@ -207,11 +205,10 @@ def __call__(self, test: T) -> T:
setattr(test, attr_name, True)
_test.TestCase.settings = self
return test # type: ignore
else:
raise InvalidArgument(
"@settings(...) can only be used as a decorator on "
"functions, or on subclasses of RuleBasedStateMachine."
)
raise InvalidArgument(
"@settings(...) can only be used as a decorator on "
"functions, or on subclasses of RuleBasedStateMachine."
)
if hasattr(_test, "_hypothesis_internal_settings_applied"):
# Can't use _hypothesis_internal_use_settings as an indicator that
# @settings was applied, because @given also assigns that attribute.
Expand Down
3 changes: 1 addition & 2 deletions hypothesis-python/src/hypothesis/control.py
Expand Up @@ -181,7 +181,6 @@ def target(observation: Union[int, float], *, label: str = "") -> Union[int, flo
f"Calling target({observation!r}, label={label!r}) would overwrite "
f"target({context.data.target_observations[label]!r}, label={label!r})"
)
else:
context.data.target_observations[label] = observation
context.data.target_observations[label] = observation

return observation
64 changes: 31 additions & 33 deletions hypothesis-python/src/hypothesis/core.py
Expand Up @@ -221,7 +221,7 @@ def decode_failure(blob):
prefix = buffer[:1]
if prefix == b"\0":
return buffer[1:]
elif prefix == b"\1":
if prefix == b"\1":
try:
return zlib.decompress(buffer[1:])
except zlib.error as err:
Expand Down Expand Up @@ -302,7 +302,7 @@ def is_invalid_test(test, original_sig, given_arguments, given_kwargs):
extra_kwargs = [
k for k in given_kwargs if k not in {p.name for p in pos_params + kwonly_params}
]
if extra_kwargs and (params == [] or params[-1].kind is not params[-1].VAR_KEYWORD):
if extra_kwargs and (not params or params[-1].kind is not params[-1].VAR_KEYWORD):
arg = extra_kwargs[0]
return invalid(
f"{test.__name__}() got an unexpected keyword argument {arg!r}, "
Expand Down Expand Up @@ -462,17 +462,16 @@ def get_random_for_wrapped_test(test, wrapped_test):

if wrapped_test._hypothesis_internal_use_seed is not None:
return Random(wrapped_test._hypothesis_internal_use_seed)
elif settings.derandomize:
if settings.derandomize:
return Random(int_from_bytes(function_digest(test)))
elif global_force_seed is not None:
if global_force_seed is not None:
return Random(global_force_seed)
else:
global _hypothesis_global_random
if _hypothesis_global_random is None:
_hypothesis_global_random = Random()
seed = _hypothesis_global_random.getrandbits(128)
wrapped_test._hypothesis_internal_use_generated_seed = seed
return Random(seed)
global _hypothesis_global_random
if _hypothesis_global_random is None:
_hypothesis_global_random = Random()
seed = _hypothesis_global_random.getrandbits(128)
wrapped_test._hypothesis_internal_use_generated_seed = seed
return Random(seed)


def process_arguments_to_given(wrapped_test, arguments, kwargs, given_kwargs, params):
Expand Down Expand Up @@ -782,27 +781,26 @@ def _execute_once_for_engine(self, data):
# block somewhere, suppressing our original StopTest.
# We raise a new one here to resume normal operation.
raise StopTest(data.testcounter) from e
else:
# The test failed by raising an exception, so we inform the
# engine that this test run was interesting. This is the normal
# path for test runs that fail.

tb = get_trimmed_traceback()
info = data.extra_information
info.__expected_traceback = format_exception(e, tb)
info.__expected_exception = e
verbose_report(info.__expected_traceback)

self.failed_normally = True

interesting_origin = get_interesting_origin(e)
if trace: # pragma: no cover
# Trace collection is explicitly disabled under coverage.
self.explain_traces[interesting_origin].add(trace)
if interesting_origin[0] == DeadlineExceeded:
self.failed_due_to_deadline = True
self.explain_traces.clear()
data.mark_interesting(interesting_origin)
# The test failed by raising an exception, so we inform the
# engine that this test run was interesting. This is the normal
# path for test runs that fail.

tb = get_trimmed_traceback()
info = data.extra_information
info.__expected_traceback = format_exception(e, tb)
info.__expected_exception = e
verbose_report(info.__expected_traceback)

self.failed_normally = True

interesting_origin = get_interesting_origin(e)
if trace: # pragma: no cover
# Trace collection is explicitly disabled under coverage.
self.explain_traces[interesting_origin].add(trace)
if interesting_origin[0] == DeadlineExceeded:
self.failed_due_to_deadline = True
self.explain_traces.clear()
data.mark_interesting(interesting_origin)

def run_engine(self):
"""Run the test function many times, on database input and generated
Expand Down Expand Up @@ -844,7 +842,7 @@ def run_engine(self):

if not self.falsifying_examples:
return
elif not (self.settings.report_multiple_bugs and pytest_shows_exceptiongroups):
if not (self.settings.report_multiple_bugs and pytest_shows_exceptiongroups):
# Pretend that we only found one failure, by discarding the others.
del self.falsifying_examples[:-1]

Expand Down
3 changes: 1 addition & 2 deletions hypothesis-python/src/hypothesis/executors.py
Expand Up @@ -61,5 +61,4 @@ def new_style_executor(runner):
old_school = executor(runner)
if old_school is default_executor:
return default_new_style_executor
else:
return lambda data, function: old_school(lambda: function(data))
return lambda data, function: old_school(lambda: function(data))
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/_array_helpers.py
Expand Up @@ -241,7 +241,7 @@ def broadcastable_shapes(
if s < min_side and s != 1:
max_dims = n
break
elif not (min_side <= 1 <= max_side or s <= max_side):
if not (min_side <= 1 <= max_side or s <= max_side):
max_dims = n
break

Expand Down Expand Up @@ -471,7 +471,7 @@ def mutually_broadcastable_shapes(
if s < min_side and s != 1:
max_dims = n
break
elif not (min_side <= 1 <= max_side or s <= max_side):
if not (min_side <= 1 <= max_side or s <= max_side):
max_dims = n
break

Expand Down
62 changes: 30 additions & 32 deletions hypothesis-python/src/hypothesis/extra/array_api.py
Expand Up @@ -227,7 +227,7 @@ def check_valid_minmax(prefix, val, info_obj):

if builtin is bool:
return st.booleans()
elif builtin is int:
if builtin is int:
iinfo = xp.iinfo(dtype)
if min_value is None:
min_value = iinfo.min
Expand All @@ -241,7 +241,7 @@ def check_valid_minmax(prefix, val, info_obj):
check_valid_minmax("max", max_value, iinfo)
check_valid_interval(min_value, max_value, "min_value", "max_value")
return st.integers(min_value=min_value, max_value=max_value)
elif builtin is float:
if builtin is float:
finfo = xp.finfo(dtype)
kw = {}

Expand Down Expand Up @@ -292,31 +292,30 @@ def check_valid_minmax(prefix, val, info_obj):
kw["exclude_max"] = exclude_max

return st.floats(width=finfo.bits, **kw)
else:
# A less-inelegant solution to support complex dtypes exists, but as
# this is currently a draft feature, we might as well wait for
# discussion of complex inspection to resolve first - a better method
# might become available soon enough.
# See https://github.com/data-apis/array-api/issues/433
for attr in ["float32", "float64", "complex64"]:
if not hasattr(xp, attr):
raise NotImplementedError(
f"Array module {xp.__name__} has no dtype {attr}, which is "
"currently required for xps.from_dtype() to work with "
"any complex dtype."
)
component_dtype = xp.float32 if dtype == xp.complex64 else xp.float64

floats = _from_dtype(
xp,
api_version,
component_dtype,
allow_nan=allow_nan,
allow_infinity=allow_infinity,
allow_subnormal=allow_subnormal,
)
# A less-inelegant solution to support complex dtypes exists, but as
# this is currently a draft feature, we might as well wait for
# discussion of complex inspection to resolve first - a better method
# might become available soon enough.
# See https://github.com/data-apis/array-api/issues/433
for attr in ["float32", "float64", "complex64"]:
if not hasattr(xp, attr):
raise NotImplementedError(
f"Array module {xp.__name__} has no dtype {attr}, which is "
"currently required for xps.from_dtype() to work with "
"any complex dtype."
)
component_dtype = xp.float32 if dtype == xp.complex64 else xp.float64

floats = _from_dtype(
xp,
api_version,
component_dtype,
allow_nan=allow_nan,
allow_infinity=allow_infinity,
allow_subnormal=allow_subnormal,
)

return st.builds(complex, floats, floats) # type: ignore[arg-type]
return st.builds(complex, floats, floats) # type: ignore[arg-type]


class ArrayStrategy(st.SearchStrategy):
Expand Down Expand Up @@ -448,8 +447,7 @@ def do_draw(self, data):
if val in seen:
elements.reject()
continue
else:
seen.add(val)
seen.add(val)
try:
result[i] = val
except Exception as e:
Expand Down Expand Up @@ -554,7 +552,7 @@ def _arrays(
xp, api_version, d, shape, elements=elements, fill=fill, unique=unique
)
)
elif isinstance(dtype, str):
if isinstance(dtype, str):
dtype = dtype_from_name(xp, dtype)

if isinstance(shape, st.SearchStrategy):
Expand All @@ -563,7 +561,7 @@ def _arrays(
xp, api_version, dtype, s, elements=elements, fill=fill, unique=unique
)
)
elif isinstance(shape, int):
if isinstance(shape, int):
shape = (shape,)
elif not isinstance(shape, tuple):
raise InvalidArgument(f"shape={shape} is not a valid shape or strategy")
Expand Down Expand Up @@ -606,7 +604,7 @@ def check_dtypes(xp: Any, dtypes: List[DataType], stubs: List[str]) -> None:
f"Array module {xp.__name__} does not have the following "
f"required dtypes in its namespace: {f_stubs}"
)
elif len(stubs) > 0:
if len(stubs) > 0:
warn_on_missing_dtypes(xp, stubs)


Expand Down Expand Up @@ -1023,7 +1021,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
3 changes: 1 addition & 2 deletions hypothesis-python/src/hypothesis/extra/cli.py
Expand Up @@ -120,8 +120,7 @@ def describe_close_matches(
matches = get_close_matches(objname, public_names)
if matches:
return f" Closest matches: {matches!r}"
else:
return ""
return ""

if classname is None:
try:
Expand Down