Skip to content

Commit 1834bbb

Browse files
committed
pyupgrade %-formatting
1 parent 94a6d20 commit 1834bbb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+182
-184
lines changed

hypothesis-python/scripts/validate_branch_check.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@
4848
print("The following were always True:")
4949
print()
5050
for c in always_true:
51-
print(" * %s" % (c,))
51+
print(f" * {c}")
5252
if always_false:
5353
print("The following were always False:")
5454
print()
5555
for c in always_false:
56-
print(" * %s" % (c,))
56+
print(f" * {c}")
5757
if failure:
5858
sys.exit(1)

hypothesis-python/src/hypothesis/_settings.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def __set__(self, obj, value):
7373
obj.__dict__[self.name] = value
7474

7575
def __delete__(self, obj):
76-
raise AttributeError("Cannot delete attribute %s" % (self.name,))
76+
raise AttributeError(f"Cannot delete attribute {self.name}")
7777

7878
@property
7979
def __doc__(self):
@@ -83,7 +83,7 @@ def __doc__(self):
8383
if self.show_default
8484
else "(dynamically calculated)"
8585
)
86-
return "%s\n\ndefault value: ``%s``" % (description, default)
86+
return f"{description}\n\ndefault value: ``{default}``"
8787

8888

8989
default_variable = DynamicVariable(None)
@@ -139,7 +139,7 @@ def __getattr__(self, name):
139139
if name in all_settings:
140140
return all_settings[name].default
141141
else:
142-
raise AttributeError("settings has no attribute %s" % (name,))
142+
raise AttributeError(f"settings has no attribute {name}")
143143

144144
def __init__(
145145
self,
@@ -279,15 +279,15 @@ def __setattr__(self, name, value):
279279
raise AttributeError("settings objects are immutable")
280280

281281
def __repr__(self):
282-
bits = ("%s=%r" % (name, getattr(self, name)) for name in all_settings)
282+
bits = ("{}={!r}".format(name, getattr(self, name)) for name in all_settings)
283283
return "settings(%s)" % ", ".join(sorted(bits))
284284

285285
def show_changed(self):
286286
bits = []
287287
for name, setting in all_settings.items():
288288
value = getattr(self, name)
289289
if value != setting.default:
290-
bits.append("%s=%r" % (name, value))
290+
bits.append(f"{name}={value!r}")
291291
return ", ".join(sorted(bits, key=len))
292292

293293
@staticmethod
@@ -437,7 +437,7 @@ class Phase(IntEnum):
437437
shrink = 4
438438

439439
def __repr__(self):
440-
return "Phase.%s" % (self.name,)
440+
return f"Phase.{self.name}"
441441

442442

443443
@unique
@@ -448,7 +448,7 @@ class HealthCheck(Enum):
448448
"""
449449

450450
def __repr__(self):
451-
return "%s.%s" % (self.__class__.__name__, self.name)
451+
return f"{self.__class__.__name__}.{self.name}"
452452

453453
@classmethod
454454
def all(cls) -> List["HealthCheck"]:
@@ -505,7 +505,7 @@ class Verbosity(IntEnum):
505505
debug = 3
506506

507507
def __repr__(self):
508-
return "Verbosity.%s" % (self.name,)
508+
return f"Verbosity.{self.name}"
509509

510510

511511
settings._define_setting(
@@ -520,7 +520,7 @@ def _validate_phases(phases):
520520
phases = tuple(phases)
521521
for a in phases:
522522
if not isinstance(a, Phase):
523-
raise InvalidArgument("%r is not a valid phase" % (a,))
523+
raise InvalidArgument(f"{a!r} is not a valid phase")
524524
return tuple(p for p in list(Phase) if p in phases)
525525

526526

@@ -538,7 +538,7 @@ def _validate_phases(phases):
538538
def _validate_stateful_step_count(x):
539539
check_type(int, x, name="stateful_step_count")
540540
if x < 1:
541-
raise InvalidArgument("stateful_step_count=%r must be at least one." % (x,))
541+
raise InvalidArgument(f"stateful_step_count={x!r} must be at least one.")
542542
return x
543543

544544

@@ -588,7 +588,7 @@ class duration(datetime.timedelta):
588588

589589
def __repr__(self):
590590
ms = self.total_seconds() * 1000
591-
return "timedelta(milliseconds=%r)" % (int(ms) if ms == int(ms) else ms,)
591+
return "timedelta(milliseconds={!r})".format(int(ms) if ms == int(ms) else ms)
592592

593593

594594
def _validate_deadline(x):

hypothesis-python/src/hypothesis/control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def target(observation: Union[int, float], *, label: str = "") -> None:
183183
context = _current_build_context.value
184184
if context is None:
185185
raise InvalidArgument("Calling target() outside of a test is invalid.")
186-
verbose_report("Saw target(observation=%r, label=%r)" % (observation, label))
186+
verbose_report(f"Saw target(observation={observation!r}, label={label!r})")
187187

188188
if label in context.data.target_observations:
189189
raise InvalidArgument(

hypothesis-python/src/hypothesis/core.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -192,18 +192,18 @@ def decode_failure(blob):
192192
try:
193193
buffer = base64.b64decode(blob)
194194
except Exception:
195-
raise InvalidArgument("Invalid base64 encoded string: %r" % (blob,))
195+
raise InvalidArgument(f"Invalid base64 encoded string: {blob!r}")
196196
prefix = buffer[:1]
197197
if prefix == b"\0":
198198
return buffer[1:]
199199
elif prefix == b"\1":
200200
try:
201201
return zlib.decompress(buffer[1:])
202202
except zlib.error:
203-
raise InvalidArgument("Invalid zlib compression for blob %r" % (blob,))
203+
raise InvalidArgument(f"Invalid zlib compression for blob {blob!r}")
204204
else:
205205
raise InvalidArgument(
206-
"Could not decode blob %r: Invalid start byte %r" % (blob, prefix)
206+
f"Could not decode blob {blob!r}: Invalid start byte {prefix!r}"
207207
)
208208

209209

@@ -218,7 +218,7 @@ def do_draw(self, data):
218218
return self.mapped_strategy.do_draw(data)
219219

220220
def __repr__(self):
221-
return "WithRunner(%r, runner=%r)" % (self.mapped_strategy, self.runner)
221+
return f"WithRunner({self.mapped_strategy!r}, runner={self.runner!r})"
222222

223223

224224
def is_invalid_test(name, original_argspec, given_arguments, given_kwargs):

hypothesis-python/src/hypothesis/database.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def __init__(self):
150150
self.data = {}
151151

152152
def __repr__(self) -> str:
153-
return "InMemoryExampleDatabase(%r)" % (self.data,)
153+
return f"InMemoryExampleDatabase({self.data!r})"
154154

155155
def fetch(self, key: bytes) -> Iterable[bytes]:
156156
yield from self.data.get(key, ())
@@ -190,7 +190,7 @@ def __init__(self, path: str) -> None:
190190
self.keypaths = {} # type: dict
191191

192192
def __repr__(self) -> str:
193-
return "DirectoryBasedExampleDatabase(%r)" % (self.path,)
193+
return f"DirectoryBasedExampleDatabase({self.path!r})"
194194

195195
def _key_path(self, key):
196196
try:

hypothesis-python/src/hypothesis/errors.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,7 @@ class NoSuchExample(HypothesisException):
3737
"""
3838

3939
def __init__(self, condition_string, extra=""):
40-
super().__init__(
41-
"No examples found of condition %s%s" % (condition_string, extra)
42-
)
40+
super().__init__(f"No examples found of condition {condition_string}{extra}")
4341

4442

4543
class Unsatisfiable(HypothesisException):

hypothesis-python/src/hypothesis/extra/django/_fields.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,7 @@ def register_field_strategy(
262262
``strategy`` must be a :class:`~hypothesis.strategies.SearchStrategy`.
263263
"""
264264
if not issubclass(field_type, (dm.Field, df.Field)):
265-
raise InvalidArgument(
266-
"field_type=%r must be a subtype of Field" % (field_type,)
267-
)
265+
raise InvalidArgument(f"field_type={field_type!r} must be a subtype of Field")
268266
check_type(st.SearchStrategy, strategy, "strategy")
269267
if field_type in _global_field_lookup:
270268
raise InvalidArgument(

hypothesis-python/src/hypothesis/extra/django/_impl.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def from_model(
9090
raise TypeError("Missing required positional argument `model`")
9191

9292
if not issubclass(m_type, dm.Model):
93-
raise InvalidArgument("model=%r must be a subtype of Model" % (model,))
93+
raise InvalidArgument(f"model={model!r} must be a subtype of Model")
9494

9595
fields_by_name = {f.name: f for f in m_type._meta.concrete_fields}
9696
for name, value in sorted(field_strategies.items()):
@@ -172,7 +172,7 @@ def from_form(
172172
# ImageField
173173
form_kwargs = form_kwargs or {}
174174
if not issubclass(form, df.BaseForm):
175-
raise InvalidArgument("form=%r must be a subtype of Form" % (form,))
175+
raise InvalidArgument(f"form={form!r} must be a subtype of Form")
176176

177177
# Forms are a little bit different from models. Model classes have
178178
# all their fields defined, whereas forms may have different fields

hypothesis-python/src/hypothesis/extra/lark.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def rule_label(self, name):
157157
return self.__rule_labels[name]
158158
except KeyError:
159159
return self.__rule_labels.setdefault(
160-
name, calc_label_from_name("LARK:%s" % (name,))
160+
name, calc_label_from_name(f"LARK:{name}")
161161
)
162162

163163
def draw_symbol(self, data, symbol, draw_state):
@@ -235,7 +235,7 @@ def from_lark(
235235
else:
236236
check_type(dict, explicit, "explicit")
237237
explicit = {
238-
k: v.map(check_explicit("explicit[%r]=%r" % (k, v)))
238+
k: v.map(check_explicit(f"explicit[{k!r}]={v!r}"))
239239
for k, v in explicit.items()
240240
}
241241
return LarkStrategy(grammar, start, explicit)

hypothesis-python/src/hypothesis/extra/numpy.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ def fill_for(elements, unique, fill, name=""):
341341
else:
342342
fill = elements
343343
else:
344-
st.check_strategy(fill, "%s.fill" % (name,) if name else "fill")
344+
st.check_strategy(fill, f"{name}.fill" if name else "fill")
345345
return fill
346346

347347

@@ -1098,7 +1098,7 @@ def _hypothesis_parse_gufunc_signature(signature, all_checks=True):
10981098
"contains shapes with more than 32 dimensions and is thus invalid."
10991099
% (signature,)
11001100
)
1101-
raise InvalidArgument("%r is not a valid gufunc signature" % (signature,))
1101+
raise InvalidArgument(f"{signature!r} is not a valid gufunc signature")
11021102
input_shapes, output_shapes = (
11031103
tuple(tuple(re.findall(_DIMENSION, a)) for a in re.findall(_SHAPE, arg_list))
11041104
for arg_list in signature.split("->")
@@ -1412,11 +1412,11 @@ def basic_indices(
14121412
order_check("dims", 0, min_dims, max_dims)
14131413
check_argument(
14141414
max_dims <= 32,
1415-
"max_dims=%r, but numpy arrays have at most 32 dimensions" % (max_dims,),
1415+
f"max_dims={max_dims!r}, but numpy arrays have at most 32 dimensions",
14161416
)
14171417
check_argument(
14181418
all(isinstance(x, int) and x >= 0 for x in shape),
1419-
"shape=%r, but all dimensions must be of integer size >= 0" % (shape,),
1419+
f"shape={shape!r}, but all dimensions must be of integer size >= 0",
14201420
)
14211421
return BasicIndexStrategy(
14221422
shape,
@@ -1476,11 +1476,11 @@ def integer_array_indices(
14761476
check_type(tuple, shape, "shape")
14771477
check_argument(
14781478
shape and all(isinstance(x, int) and x > 0 for x in shape),
1479-
"shape=%r must be a non-empty tuple of integers > 0" % (shape,),
1479+
f"shape={shape!r} must be a non-empty tuple of integers > 0",
14801480
)
14811481
check_strategy(result_shape, "result_shape")
14821482
check_argument(
1483-
np.issubdtype(dtype, np.integer), "dtype=%r must be an integer dtype" % (dtype,)
1483+
np.issubdtype(dtype, np.integer), f"dtype={dtype!r} must be an integer dtype"
14841484
)
14851485
signed = np.issubdtype(dtype, np.signedinteger)
14861486

hypothesis-python/src/hypothesis/extra/pandas/impl.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,10 @@ def elements_and_dtype(elements, dtype, source=None):
6464
if source is None:
6565
prefix = ""
6666
else:
67-
prefix = "%s." % (source,)
67+
prefix = f"{source}."
6868

6969
if elements is not None:
70-
st.check_strategy(elements, "%selements" % (prefix,))
70+
st.check_strategy(elements, f"{prefix}elements")
7171
else:
7272
with check("dtype is not None"):
7373
if dtype is None:
@@ -82,7 +82,7 @@ def elements_and_dtype(elements, dtype, source=None):
8282
with check("is_categorical_dtype"):
8383
if is_categorical_dtype(dtype):
8484
raise InvalidArgument(
85-
"%sdtype is categorical, which is currently unsupported" % (prefix,)
85+
f"{prefix}dtype is categorical, which is currently unsupported"
8686
)
8787

8888
dtype = try_convert(np.dtype, dtype, "dtype")
@@ -92,7 +92,7 @@ def elements_and_dtype(elements, dtype, source=None):
9292
elif dtype is not None:
9393

9494
def convert_element(value):
95-
name = "draw(%selements)" % (prefix,)
95+
name = f"draw({prefix}elements)"
9696
try:
9797
return np.array([value], dtype=dtype)[0]
9898
except TypeError:
@@ -102,7 +102,7 @@ def convert_element(value):
102102
)
103103
except ValueError:
104104
raise InvalidArgument(
105-
"Cannot convert %s=%r to type %s" % (name, value, dtype.str)
105+
f"Cannot convert {name}={value!r} to type {dtype.str}"
106106
)
107107

108108
elements = elements.map(convert_element)
@@ -524,7 +524,7 @@ def row():
524524
)
525525

526526
if c.name in column_names:
527-
raise InvalidArgument("duplicate definition of column name %r" % (c.name,))
527+
raise InvalidArgument(f"duplicate definition of column name {c.name!r}")
528528

529529
column_names.add(c.name)
530530

hypothesis-python/src/hypothesis/extra/pytestplugin.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def pytest_report_header(config):
9595
settings_str = settings.get_profile(profile).show_changed()
9696
if settings_str != "":
9797
settings_str = " -> %s" % (settings_str)
98-
return "hypothesis profile %r%s" % (profile, settings_str)
98+
return f"hypothesis profile {profile!r}{settings_str}"
9999

100100
def pytest_configure(config):
101101
core.running_under_pytest = True
@@ -105,7 +105,7 @@ def pytest_configure(config):
105105
verbosity_name = config.getoption(VERBOSITY_OPTION)
106106
if verbosity_name:
107107
verbosity_value = Verbosity[verbosity_name]
108-
profile_name = "%s-with-%s-verbosity" % (
108+
profile_name = "{}-with-{}-verbosity".format(
109109
settings._current_profile,
110110
verbosity_name,
111111
)

hypothesis-python/src/hypothesis/internal/cache.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def unpin(self, key):
141141
i = self.keys_to_indices[key]
142142
entry = self.data[i]
143143
if entry.pins == 0:
144-
raise ValueError("Key %r has not been pinned" % (key,))
144+
raise ValueError(f"Key {key!r} has not been pinned")
145145
entry.pins -= 1
146146
if entry.pins == 0:
147147
self.__pinned_entry_count -= 1
@@ -159,7 +159,7 @@ def clear(self):
159159
self.__pinned_entry_count = 0
160160

161161
def __repr__(self):
162-
return "{%s}" % (", ".join("%r: %r" % (e.key, e.value) for e in self.data),)
162+
return "{{{}}}".format(", ".join(f"{e.key!r}: {e.value!r}" for e in self.data))
163163

164164
def new_entry(self, key, value):
165165
"""Called when a key is written that does not currently appear in the

hypothesis-python/src/hypothesis/internal/charmap.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def as_general_categories(cats, name="cats"):
146146
out.update(x for x in cs if x.startswith(c))
147147
elif c not in cs:
148148
raise InvalidArgument(
149-
"In %s=%r, %r is not a valid Unicode category." % (name, cats, c)
149+
f"In {name}={cats!r}, {c!r} is not a valid Unicode category."
150150
)
151151
return tuple(c for c in cs if c in out)
152152

0 commit comments

Comments
 (0)