Skip to content

Commit

Permalink
STY: manual fixes for UP031 rule (use string format specifiers)
Browse files Browse the repository at this point in the history
  • Loading branch information
neutrinoceros committed May 7, 2024
1 parent 5c9407a commit 6902032
Show file tree
Hide file tree
Showing 32 changed files with 69 additions and 62 deletions.
2 changes: 1 addition & 1 deletion yt/_maintenance/backports.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def __new__(cls, *values):
if len(values) == 3:
# check that errors argument is a string
if not isinstance(values[2], str):
raise TypeError("errors must be a string, not %r" % (values[2]))
raise TypeError("errors must be a string, not %r" % (values[2])) # noqa: UP031
value = str(*values)
member = str.__new__(cls, value)
member._value_ = value
Expand Down
2 changes: 1 addition & 1 deletion yt/data_objects/analyzer_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class QuantityProxy(AnalysisTask):
def __repr__(self):
# Stolen from YTDataContainer.__repr__
s = f"{self.__class__.__name__}: "
s += ", ".join(["%s" % list(self.args)])
s += ", ".join([str(list(self.args))])
s += ", ".join(f"{k}={v}" for k, v in self.kwargs.items())
return s

Expand Down
5 changes: 3 additions & 2 deletions yt/data_objects/construction_data_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,10 +880,11 @@ def get_data(self, fields=None):
fill, gen, part, alias = self._split_fields(fields_to_get)
except NeedsGridType as e:
if self._num_ghost_zones == 0:
num_ghost_zones = self._num_ghost_zones
raise RuntimeError(
"Attempting to access a field that needs ghost zones, but "
"num_ghost_zones = %s. You should create the covering grid "
"with nonzero num_ghost_zones." % self._num_ghost_zones
f"{num_ghost_zones = }. You should create the covering grid "
"with nonzero num_ghost_zones."
) from e
else:
raise
Expand Down
2 changes: 1 addition & 1 deletion yt/data_objects/level_sets/clump_info_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _distance_to_main_clump(clump, units="pc"):
distance = np.sqrt(((master_com - my_com) ** 2).sum())
distance.convert_to_units("pc")
return (
"Distance from master center of mass: %%.6e %s." % units,
f"Distance from master center of mass: %.6e {units}.",
distance.in_units(units),
)

Expand Down
2 changes: 1 addition & 1 deletion yt/data_objects/static_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,7 +1395,7 @@ def set_units(self):
new_unit,
my_u.base_value / (1 + self.current_redshift),
dimensions.length,
"\\rm{%s}/(1+z)" % my_unit,
f"\\rm{{{my_unit}}}/(1+z)",
prefixable=True,
)
self.unit_registry.modify("a", 1 / (1 + self.current_redshift))
Expand Down
2 changes: 1 addition & 1 deletion yt/fields/derived_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def get_label(self, projected=False):
name = self.display_name

# Start with the field name
data_label = r"$\rm{%s}" % name
data_label = rf"$\rm{{{name}}}"

# Grab the correct units
if projected:
Expand Down
8 changes: 4 additions & 4 deletions yt/fields/particle_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def particle_count(field, data):
function=particle_count,
validators=[ValidateSpatial()],
units="",
display_name=r"\mathrm{%s Count}" % ptype_dn,
display_name=rf"\mathrm{{{ptype_dn} Count}}",
)

def particle_mass(field, data):
Expand All @@ -125,7 +125,7 @@ def particle_mass(field, data):
sampling_type="cell",
function=particle_mass,
validators=[ValidateSpatial()],
display_name=r"\mathrm{%s Mass}" % ptype_dn,
display_name=rf"\mathrm{{{ptype_dn} Mass}}",
units=unit_system["mass"],
)

Expand All @@ -144,7 +144,7 @@ def particle_density(field, data):
sampling_type="cell",
function=particle_density,
validators=[ValidateSpatial()],
display_name=r"\mathrm{%s Density}" % ptype_dn,
display_name=rf"\mathrm{{{ptype_dn} Density}}",
units=unit_system["density"],
)

Expand All @@ -160,7 +160,7 @@ def particle_cic(field, data):
sampling_type="cell",
function=particle_cic,
validators=[ValidateSpatial()],
display_name=r"\mathrm{%s CIC Density}" % ptype_dn,
display_name=rf"\mathrm{{{ptype_dn} CIC Density}}",
units=unit_system["density"],
)

Expand Down
2 changes: 1 addition & 1 deletion yt/fields/vector_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def _los_field(field, data):
function=_los_field,
units=field_units,
validators=validators,
display_name=r"\mathrm{Line of Sight %s}" % basename.capitalize(),
display_name=rf"\mathrm{{Line of Sight {basename.capitalize()}}}",
)


Expand Down
4 changes: 2 additions & 2 deletions yt/frontends/adaptahop/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def _guess_headers_from_file(self, filename) -> None:
pass

if not ok:
raise OSError("Could not read headers from file %s" % filename)
raise OSError(f"Could not read headers from file {filename}")

istart = fpu.tell()
fpu.seek(0, 2)
Expand All @@ -130,7 +130,7 @@ def _guess_headers_from_file(self, filename) -> None:
continue

if not ok:
raise OSError("Could not guess fields from file %s" % filename)
raise OSError(f"Could not guess fields from file {filename}")

self._header_attributes = header_attributes
self._halo_attributes = attributes
Expand Down
4 changes: 2 additions & 2 deletions yt/frontends/boxlib/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ def setup_fluid_fields(self):
sampling_type="cell",
function=func,
units=unit_system["density"],
display_name=r"\rho %s" % tex_label,
display_name=rf"\rho {tex_label}",
)

# Most of the time our species will be of the form
Expand All @@ -507,7 +507,7 @@ def setup_fluid_fields(self):

elif field.startswith("omegadot("):
nice_name, tex_label = _nice_species_name(field)
display_name = r"\dot{\omega}\left[%s\right]" % tex_label
display_name = rf"\dot{{\omega}}\left[{tex_label}\right]"
# Overwrite field to use nicer tex_label'ed display_name
self.add_output_field(
("boxlib", field),
Expand Down
2 changes: 1 addition & 1 deletion yt/frontends/enzo/simulation_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def _set_units(self):
new_unit,
self.unit_registry.lut[my_unit][0],
dimensions.length,
"\\rm{%s}/(1+z)" % my_unit,
f"\\rm{{{my_unit}}}/(1+z)",
prefixable=True,
)
self.length_unit = self.quan(
Expand Down
2 changes: 1 addition & 1 deletion yt/frontends/fits/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,6 @@ def _repr_html_(self):
img = base64.b64encode(f.read()).decode()
ret += (
r'<img style="max-width:100%%;max-height:100%%;" '
r'src="data:image/png;base64,%s"><br>' % img
rf'src="data:image/png;base64,{img}"><br>'
)
return ret
2 changes: 1 addition & 1 deletion yt/frontends/flash/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def _set_code_unit_attributes(self):
else:
raise RuntimeError(
"Runtime parameter unitsystem with "
"value %s is unrecognized" % self["unitsystem"]
f"value {self['unitsystem']} is unrecognized"
)
else:
b_factor = 1.0
Expand Down
2 changes: 1 addition & 1 deletion yt/frontends/gadget/simulation_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def _set_units(self):
new_unit,
self.unit_registry.lut[my_unit][0],
dimensions.length,
"\\rm{%s}/(1+z)" % my_unit,
f"\\rm{{{my_unit}}}/(1+z)",
prefixable=True,
)
self.length_unit = self.quan(
Expand Down
6 changes: 3 additions & 3 deletions yt/frontends/ramses/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def __init__(
elif num_ghost_zones < 0:
raise RuntimeError(
"Cannot initialize a domain subset with a negative number "
"of ghost zones, was called with num_ghost_zones=%s" % num_ghost_zones
f"of ghost zones, was called with {num_ghost_zones=}"
)

@property
Expand Down Expand Up @@ -1038,8 +1038,8 @@ def caster(val):

if rheader["ordering type"] != "hilbert" and self._bbox is not None:
raise NotImplementedError(
"The ordering %s is not compatible with the `bbox` argument."
% rheader["ordering type"]
f"The ordering {rheader['ordering type']} "
"is not compatible with the `bbox` argument."
)
self.parameters.update(rheader)
self.domain_left_edge = np.zeros(3, dtype="float64")
Expand Down
4 changes: 2 additions & 2 deletions yt/frontends/sph/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ def sph_smoothing_style(self):
def sph_smoothing_style(self, value):
if value not in self._sph_smoothing_styles:
raise ValueError(
"Smoothing style not implemented: %s, please "
"select one of the following: " % value,
f"Smoothing style not implemented: {value}, "
"please select one of the following: ",
self._sph_smoothing_styles,
)

Expand Down
2 changes: 1 addition & 1 deletion yt/frontends/tipsy/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _parse_parameter_file(self):
# the snapshot time and particle counts.

f = open(self.parameter_filename, "rb")
hh = self.endian + "".join("%s" % (b) for a, b in self._header_spec)
hh = self.endian + "".join(str(b) for a, b in self._header_spec)
hvals = {
a: c
for (a, b), c in zip(
Expand Down
31 changes: 18 additions & 13 deletions yt/funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,12 +1086,20 @@ def array_like_field(data, x, field):
return data.ds.quan(x, units)


def _full_type_name(obj: object = None, /, *, cls: Optional[type] = None) -> str:
if cls is not None and obj is not None:
raise TypeError("_full_type_name takes an object or a class, but not both")
if cls is None:
cls = obj.__class__
prefix = f"{cls.__module__}." if cls.__module__ != "builtins" else ""
return f"{prefix}{cls.__name__}"


def validate_3d_array(obj):
if not is_sequence(obj) or len(obj) != 3:
raise TypeError(
"Expected an array of size (3,), received '{}' of length {}".format(
str(type(obj)).split("'")[1], len(obj)
)
f"Expected an array of size (3,), "
f"received {_full_type_name(obj)!r} of length {len(obj)}"
)


Expand Down Expand Up @@ -1135,23 +1143,21 @@ def validate_float(obj):
):
raise TypeError(
"Expected a numeric value (or tuple of format "
"(float, String)), received an inconsistent tuple "
"'%s'." % str(obj)
f"(float, String)), received an inconsistent tuple {str(obj)!r}."
)
else:
return
if is_sequence(obj) and (len(obj) != 1 or not isinstance(obj[0], numeric_type)):
raise TypeError(
"Expected a numeric value (or size-1 array), "
"received '{}' of length {}".format(str(type(obj)).split("'")[1], len(obj))
f"received {_full_type_name(obj)!r} of length {len(obj)}"
)


def validate_sequence(obj):
if obj is not None and not is_sequence(obj):
raise TypeError(
"Expected an iterable object, "
"received '%s'" % str(type(obj)).split("'")[1]
"Expected an iterable object, " f"received {_full_type_name(obj)!r}"
)


Expand Down Expand Up @@ -1181,9 +1187,8 @@ def is_valid_field_key(key):
def validate_object(obj, data_type):
if obj is not None and not isinstance(obj, data_type):
raise TypeError(
"Expected an object of '{}' type, received '{}'".format(
str(data_type).split("'")[1], str(type(obj)).split("'")[1]
)
f"Expected an object of {_full_type_name(cls=data_type)!r} type, "
f"received {_full_type_name(obj)!r}"
)


Expand All @@ -1209,13 +1214,13 @@ def validate_center(center):
raise TypeError(
"Expected 'center' to be in ['c', 'center', "
"'m', 'max', 'min'] or the prefix to be "
"'max_'/'min_', received '%s'." % center
f"'max_'/'min_', received {center!r}."
)
elif not isinstance(center, (numeric_type, YTQuantity)) and not is_sequence(center):
raise TypeError(
"Expected 'center' to be a numeric object of type "
"list/tuple/np.ndarray/YTArray/YTQuantity, "
"received '%s'." % str(type(center)).split("'")[1]
f"received {_full_type_name(center)}."
)


Expand Down
4 changes: 2 additions & 2 deletions yt/geometry/coordinates/cartesian_coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,8 +593,8 @@ def _ortho_pixelize(
mask = mask.transpose()
else:
raise NotImplementedError(
"A pixelization routine has not been implemented for %s "
"data objects" % str(type(data_source))
"A pixelization routine has not been implemented for "
f"{type(data_source)} data objects"
)
buff = buff.transpose()
mask = mask.transpose()
Expand Down
2 changes: 1 addition & 1 deletion yt/utilities/cosmology.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def __init__(
new_unit,
my_u.base_value,
dimensions.length,
"\\rm{%s}/(1+z)" % my_unit,
f"\\rm{{{my_unit}}}/(1+z)",
prefixable=True,
)
self.unit_registry = unit_registry
Expand Down
4 changes: 2 additions & 2 deletions yt/utilities/on_demand_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ def __init__(self, pkg_name, exc: Optional[BaseException] = None):
# relatively short. Discussion related to this is in
# yt-project/yt#1966
self.error = ImportError(
"This functionality requires the %s "
"package to be installed." % self.pkg_name
f"This functionality requires the {self.pkg_name} "
"package to be installed."
)
else:
self.error = ImportError(
Expand Down
2 changes: 1 addition & 1 deletion yt/utilities/particle_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, ds, num_particles, field_list, ptype="io"):
except Exception as e:
raise KeyError(
"You must specify position fields: "
+ " ".join("particle_position_%s" % ax for ax in "xyz")
+ " ".join(f"particle_position_{ax}" for ax in "xyz")
) from e
self.index_index = self.field_list.index((ptype, "particle_index"))

Expand Down
4 changes: 2 additions & 2 deletions yt/visualization/_commons.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ def get_default_from_config(data_source, *, field, keys, defaults):

def _get_units_label(units: str) -> str:
if r"\frac" in units:
return r"$\ \ \left(%s\right)$" % units
return rf"$\ \ \left({units}\right)$"
elif units:
return r"$\ \ (%s)$" % units
return rf"$\ \ ({units})$"
else:
return ""
2 changes: 1 addition & 1 deletion yt/visualization/fixed_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ def _generate_image_and_mask(self, item) -> None:
norm = self.ds.quan(dpx * dpy, "code_length**2").in_base()
buff /= norm.v
units = data.units / norm.units
info["label"] = "%s $\\rm{Density}$" % info["label"]
info["label"] += " $\\rm{Density}$"
else:
units = data.units

Expand Down
2 changes: 1 addition & 1 deletion yt/visualization/image_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def write_bitmap(bitmap_array, filename, max_val=None, transpose=False):
if len(bitmap_array.shape) != 3 or bitmap_array.shape[-1] not in (3, 4):
raise RuntimeError(
"Expecting image array of shape (N,M,3) or "
"(N,M,4), received %s" % str(bitmap_array.shape)
f"(N,M,4), received {str(bitmap_array.shape)}"
)

if bitmap_array.dtype != np.uint8:
Expand Down
4 changes: 2 additions & 2 deletions yt/visualization/plot_modifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -1244,9 +1244,9 @@ def __call__(self, plot):
y[i] = right_edge_y[n] - (12 * (yy1 - yy0) / ypix)
else:
raise RuntimeError(
"Unrecognized id_loc value ('%s'). "
f"Unrecognized id_loc value ({self.id_loc!r}). "
"Allowed values are 'lower left', lower right', "
"'upper left', and 'upper right'." % self.id_loc
"'upper left', and 'upper right'."
)
xi, yi = self._sanitize_xy_order(plot, x[i], y[i])
plot._axes.text(xi, yi, "%d" % block_ids[n], clip_on=True)
Expand Down
4 changes: 2 additions & 2 deletions yt/visualization/plot_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -1195,9 +1195,9 @@ def _setup_plots(self):
if colorbar_label is None:
colorbar_label = image.info["label"]
if getattr(self, "moment", 1) == 2:
colorbar_label = "%s \\rm{Standard Deviation}" % colorbar_label
colorbar_label = f"{colorbar_label} \\rm{{Standard Deviation}}"
if hasattr(self, "projected"):
colorbar_label = "$\\rm{Projected }$ %s" % colorbar_label
colorbar_label = f"$\\rm{{Projected }}$ {colorbar_label}"
if units is not None and units != "":
colorbar_label += _get_units_label(units)

Expand Down
4 changes: 2 additions & 2 deletions yt/visualization/tests/test_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ def test_suffix_clashing(ext, simple_sliceplot, tmp_path):

target = (tmp_path / "myfile").with_suffix(ext)
expected_warning = re.compile(
r"Received two valid image formats '%s' \(from filename\) "
r"and 'png' \(from suffix\)\. The former is ignored\." % ext[1:]
rf"Received two valid image formats {ext.removeprefix('.')!r} "
r"\(from filename\) and 'png' \(from suffix\)\. The former is ignored\."
)

with pytest.warns(UserWarning, match=expected_warning):
Expand Down
Loading

0 comments on commit 6902032

Please sign in to comment.