Skip to content

Commit

Permalink
f"{var=}" is nice
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD committed Jun 27, 2023
1 parent f6e50ab commit dc28f3c
Show file tree
Hide file tree
Showing 24 changed files with 78 additions and 91 deletions.
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def __init__(
if database not in (not_set, None): # type: ignore
raise InvalidArgument(
"derandomize=True implies database=None, so passing "
f"database={database!r} too is invalid."
f"{database=} too is invalid."
)
database = None

Expand Down Expand Up @@ -191,7 +191,7 @@ def __call__(self, test: T) -> T:
if not callable(_test):
raise InvalidArgument(
"settings objects can be called as a decorator with @given, "
f"but decorated test={test!r} is not callable."
f"but decorated {test=} is not callable."
)
if inspect.isclass(test):
from hypothesis.stateful import RuleBasedStateMachine
Expand Down
8 changes: 4 additions & 4 deletions hypothesis-python/src/hypothesis/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def target(observation: Union[int, float], *, label: str = "") -> Union[int, flo
"""
check_type((int, float), observation, "observation")
if not math.isfinite(observation):
raise InvalidArgument(f"observation={observation!r} must be a finite float.")
raise InvalidArgument(f"{observation=} must be a finite float.")
check_type(str, label, "label")

context = _current_build_context.value
Expand All @@ -215,12 +215,12 @@ def target(observation: Union[int, float], *, label: str = "") -> Union[int, flo
"Calling target() outside of a test is invalid. "
"Consider guarding this call with `if currently_in_test_context(): ...`"
)
verbose_report(f"Saw target(observation={observation!r}, label={label!r})")
verbose_report(f"Saw target({observation!r}, {label=})")

if label in context.data.target_observations:
raise InvalidArgument(
f"Calling target({observation!r}, label={label!r}) would overwrite "
f"target({context.data.target_observations[label]!r}, label={label!r})"
f"Calling target({observation!r}, {label=}) would overwrite "
f"target({context.data.target_observations[label]!r}, {label=})"
)
else:
context.data.target_observations[label] = observation
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def test(x):
)
):
raise InvalidArgument(
f"raises={raises!r} must be an exception type or tuple of exception types"
f"{raises=} must be an exception type or tuple of exception types"
)
if condition:
self._this_example = attr.evolve(
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _db_for_path(path=None):
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={path!r}"
f"database for this session. {path=}"
)
)
return InMemoryExampleDatabase()
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 @@ -294,7 +294,7 @@ def _hypothesis_parse_gufunc_signature(signature, all_checks=True):
"Hypothesis does not yet support generalised ufunc signatures "
"with multiple output arrays - mostly because we don't know of "
"anyone who uses them! Please get in touch with us to fix that."
f"\n (signature={signature!r})"
f"\n ({signature=})"
)
if re.match(
(
Expand All @@ -305,7 +305,7 @@ def _hypothesis_parse_gufunc_signature(signature, all_checks=True):
signature,
):
raise InvalidArgument(
f"signature={signature!r} matches Numpy's regex for gufunc signatures, "
f"{signature=} matches Numpy's regex for gufunc signatures, "
f"but contains shapes with more than {NDIM_MAX} dimensions and is thus invalid."
)
raise InvalidArgument(f"{signature!r} is not a valid gufunc signature")
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/extra/_patching.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def make_patch(triples, *, msg="Hypothesis: add explicit examples", when=None):


def save_patch(patch: str, *, slug: str = "") -> Path: # pragma: no cover
assert re.fullmatch(r"|[a-z]+-", slug), f"malformed slug={slug!r}"
assert re.fullmatch(r"|[a-z]+-", slug), f"malformed {slug=}"
now = date.today().isoformat()
cleaned = re.sub(r"^Date: .+?$", "", patch, count=1, flags=re.MULTILINE)
hash8 = hashlib.sha1(cleaned.encode()).hexdigest()[:8]
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 @@ -563,7 +563,7 @@ def _arrays(
raise InvalidArgument(f"shape={shape} is not a valid shape or strategy")
check_argument(
all(isinstance(x, int) and x >= 0 for x in shape),
f"shape={shape!r}, but all dimensions must be non-negative integers.",
f"{shape=}, but all dimensions must be non-negative integers.",
)

if elements is None:
Expand Down Expand Up @@ -802,7 +802,7 @@ def indices(
check_type(tuple, shape, "shape")
check_argument(
all(isinstance(x, int) and x >= 0 for x in shape),
f"shape={shape!r}, but all dimensions must be non-negative integers.",
f"{shape=}, but all dimensions must be non-negative integers.",
)
check_type(bool, allow_newaxis, "allow_newaxis")
check_type(bool, allow_ellipsis, "allow_ellipsis")
Expand Down Expand Up @@ -896,15 +896,15 @@ def make_strategies_namespace(
check_argument(
isinstance(xp.__array_api_version__, str)
and xp.__array_api_version__ in RELEASED_VERSIONS,
f"xp.__array_api_version__={xp.__array_api_version__!r}, but it must "
f"{xp.__array_api_version__=}, but it must "
f"be a valid version string {RELEASED_VERSIONS}. {not_available_msg}",
)
api_version = xp.__array_api_version__
inferred_version = True
else:
check_argument(
isinstance(api_version, str) and api_version in NOMINAL_VERSIONS,
f"api_version={api_version!r}, but it must be None, or a valid version "
f"{api_version=}, but it must be None, or a valid version "
f"string in {RELEASED_VERSIONS}. {not_available_msg}",
)
inferred_version = False
Expand Down
6 changes: 3 additions & 3 deletions hypothesis-python/src/hypothesis/extra/django/_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def _for_form_ip(field):
return st.ip_addresses(v=4).map(str)
if validate_ipv6_address in field.default_validators:
return _ipv6_strings
raise ResolutionFailed(f"No IP version validator on field={field!r}")
raise ResolutionFailed(f"No IP version validator on {field=}")


@register_for(dm.DecimalField)
Expand Down Expand Up @@ -275,11 +275,11 @@ def register_field_strategy(
``strategy`` must be a :class:`~hypothesis.strategies.SearchStrategy`.
"""
if not issubclass(field_type, (dm.Field, df.Field)):
raise InvalidArgument(f"field_type={field_type!r} must be a subtype of Field")
raise InvalidArgument(f"{field_type=} must be a subtype of Field")
check_type(st.SearchStrategy, strategy, "strategy")
if field_type in _global_field_lookup:
raise InvalidArgument(
f"field_type={field_type!r} already has a registered "
f"{field_type=} already has a registered "
f"strategy ({_global_field_lookup[field_type]!r})"
)
if issubclass(field_type, dm.AutoField):
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/django/_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def from_model(
a field which has a default value instead of using the default.
"""
if not issubclass(model, dm.Model):
raise InvalidArgument(f"model={model!r} must be a subtype of Model")
raise InvalidArgument(f"{model=} must be a subtype of Model")

fields_by_name = {f.name: f for f in model._meta.concrete_fields}
for name, value in sorted(field_strategies.items()):
Expand Down Expand Up @@ -165,7 +165,7 @@ def from_form(
# ImageField
form_kwargs = form_kwargs or {}
if not issubclass(form, df.BaseForm):
raise InvalidArgument(f"form={form!r} must be a subtype of Form")
raise InvalidArgument(f"{form=} must be a subtype of Form")

# Forms are a little bit different from models. Model classes have
# all their fields defined, whereas forms may have different fields
Expand Down
10 changes: 5 additions & 5 deletions hypothesis-python/src/hypothesis/extra/ghostwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,7 @@ def test_fuzz_compile(pattern, flags):
or :func:`~hypothesis.strategies.binary`. After that, you have a test!
"""
if not callable(func):
raise InvalidArgument(f"Got non-callable func={func!r}")
raise InvalidArgument(f"Got non-callable {func=}")
except_ = _check_except(except_)
_check_style(style)

Expand Down Expand Up @@ -1389,7 +1389,7 @@ def test_idempotent_timsort(seq):
assert result == repeat, (result, repeat)
"""
if not callable(func):
raise InvalidArgument(f"Got non-callable func={func!r}")
raise InvalidArgument(f"Got non-callable {func=}")
except_ = _check_except(except_)
_check_style(style)

Expand Down Expand Up @@ -1628,14 +1628,14 @@ def binary_operation(
)
"""
if not callable(func):
raise InvalidArgument(f"Got non-callable func={func!r}")
raise InvalidArgument(f"Got non-callable {func=}")
except_ = _check_except(except_)
_check_style(style)
check_type(bool, associative, "associative")
check_type(bool, commutative, "commutative")
if distributes_over is not None and not callable(distributes_over):
raise InvalidArgument(
f"distributes_over={distributes_over!r} must be an operation which "
f"{distributes_over=} must be an operation which "
f"distributes over {func.__name__}"
)
if not any([associative, commutative, identity, distributes_over]):
Expand Down Expand Up @@ -1811,7 +1811,7 @@ def ufunc(
hypothesis write numpy.matmul
"""
if not _is_probably_ufunc(func):
raise InvalidArgument(f"func={func!r} does not seem to be a ufunc")
raise InvalidArgument(f"{func=} does not seem to be a ufunc")
except_ = _check_except(except_)
_check_style(style)

Expand Down
6 changes: 3 additions & 3 deletions hypothesis-python/src/hypothesis/extra/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,7 +885,7 @@ def basic_indices(
check_type(tuple, shape, "shape")
check_argument(
all(isinstance(x, int) and x >= 0 for x in shape),
f"shape={shape!r}, but all dimensions must be non-negative integers.",
f"{shape=}, but all dimensions must be non-negative integers.",
)
check_type(bool, allow_ellipsis, "allow_ellipsis")
check_type(bool, allow_newaxis, "allow_newaxis")
Expand Down Expand Up @@ -978,11 +978,11 @@ def integer_array_indices(
check_type(tuple, shape, "shape")
check_argument(
shape and all(isinstance(x, int) and x > 0 for x in shape),
f"shape={shape!r} must be a non-empty tuple of integers > 0",
f"{shape=} must be a non-empty tuple of integers > 0",
)
check_strategy(result_shape, "result_shape")
check_argument(
np.issubdtype(dtype, np.integer), f"dtype={dtype!r} must be an integer dtype"
np.issubdtype(dtype, np.integer), f"{dtype=} must be an integer dtype"
)
signed = np.issubdtype(dtype, np.signedinteger)

Expand Down
8 changes: 4 additions & 4 deletions hypothesis-python/src/hypothesis/extra/pandas/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ def elements_and_dtype(elements, dtype, source=None):

if isinstance(dtype, type) and issubclass(dtype, IntegerDtype):
raise InvalidArgument(
f"Passed dtype={dtype!r} is a dtype class, please pass in an instance of this class."
f"Passed {dtype=} is a dtype class, please pass in an instance of this class."
"Otherwise it would be treated as dtype=object"
)

if isinstance(dtype, type) and np.dtype(dtype).kind == "O" and dtype is not object:
err_msg = f"Passed dtype={dtype!r} is not a valid Pandas dtype."
err_msg = f"Passed {dtype=} is not a valid Pandas dtype."
if issubclass(dtype, datetime):
err_msg += ' To generate valid datetimes, pass `dtype="datetime64[ns]"`'
raise InvalidArgument(err_msg)
Expand All @@ -109,7 +109,7 @@ def elements_and_dtype(elements, dtype, source=None):

if isinstance(dtype, st.SearchStrategy):
raise InvalidArgument(
f"Passed dtype={dtype!r} is a strategy, but we require a concrete dtype "
f"Passed {dtype=} is a strategy, but we require a concrete dtype "
"here. See https://stackoverflow.com/q/74355937 for workaround patterns."
)

Expand Down Expand Up @@ -654,7 +654,7 @@ def just_draw_columns(draw):
value, (float, int, str, bool, datetime, timedelta)
):
raise ValueError(
f"Failed to add value={value!r} to column "
f"Failed to add {value=} to column "
f"{c.name} with dtype=None. Maybe passing "
"dtype=object would help?"
) from err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ def incorporate(self, value):
self.check_invariants(value)
if not self.left_is_better(value, self.current):
if value != self.current and (value == value):
self.debug(
f"Rejected {value!r} as worse than self.current={self.current!r}"
)
self.debug(f"Rejected {value!r} as worse than {self.current=}")
return False
if value in self.__seen:
return False
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/internal/entropy.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def my_WORKING_hook():
register_random(rng)
"""
if not (hasattr(r, "seed") and hasattr(r, "getstate") and hasattr(r, "setstate")):
raise InvalidArgument(f"r={r!r} does not have all the required methods")
raise InvalidArgument(f"{r=} does not have all the required methods")

if r in RANDOMS_TO_MANAGE.values():
return
Expand Down
2 changes: 1 addition & 1 deletion hypothesis-python/src/hypothesis/stateful.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def __repr__(self):
consume = self.__reference_strategy.consume
if consume is False:
return f"Bundle(name={self.name!r})"
return f"Bundle(name={self.name!r}, consume={consume!r})"
return f"Bundle(name={self.name!r}, {consume=})"

def calc_is_empty(self, recur):
# We assume that a bundle will grow over time
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ def describe_targets(best_targets):
return []
elif len(best_targets) == 1:
label, score = next(iter(best_targets.items()))
return [f"Highest target score: {score:g} (label={label!r})"]
return [f"Highest target score: {score:g} ({label=})"]
else:
lines = ["Highest target scores:"]
for label, score in sorted(best_targets.items(), key=lambda x: x[::-1]):
lines.append(f"{score:>16g} (label={label!r})")
lines.append(f"{score:>16g} ({label=})")
return lines


Expand Down
Loading

0 comments on commit dc28f3c

Please sign in to comment.