Skip to content

Commit

Permalink
STY: Apply ruff/flake8-implicit-str-concat rule ISC001 (#12602)
Browse files Browse the repository at this point in the history
  • Loading branch information
DimitriPapadopoulos committed May 15, 2024
1 parent 4cffc34 commit 5b1c49e
Show file tree
Hide file tree
Showing 72 changed files with 129 additions and 163 deletions.
20 changes: 9 additions & 11 deletions .github/actions/rename_towncrier/rename_towncrier.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,22 @@
from github import Github
from tomllib import loads

event_name = os.getenv('GITHUB_EVENT_NAME', 'pull_request')
if not event_name.startswith('pull_request'):
print(f'No-op for {event_name}')
event_name = os.getenv("GITHUB_EVENT_NAME", "pull_request")
if not event_name.startswith("pull_request"):
print(f"No-op for {event_name}")
sys.exit(0)
if 'GITHUB_EVENT_PATH' in os.environ:
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as fin:
if "GITHUB_EVENT_PATH" in os.environ:
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as fin:
event = json.load(fin)
pr_num = event['number']
basereponame = event['pull_request']['base']['repo']['full_name']
pr_num = event["number"]
basereponame = event["pull_request"]["base"]["repo"]["full_name"]
real = True
else: # local testing
pr_num = 12318 # added some towncrier files
basereponame = "mne-tools/mne-python"
real = False

g = Github(os.environ.get('GITHUB_TOKEN'))
g = Github(os.environ.get("GITHUB_TOKEN"))
baserepo = g.get_repo(basereponame)

# Grab config from upstream's default branch
Expand All @@ -45,9 +45,7 @@
assert directory.endswith("/"), directory

file_re = re.compile(rf"^{directory}({type_pipe})\.rst$")
found_stubs = [
f for f in modified_files if file_re.match(f)
]
found_stubs = [f for f in modified_files if file_re.match(f)]
for stub in found_stubs:
fro = stub
to = file_re.sub(rf"{directory}{pr_num}.\1.rst", fro)
Expand Down
2 changes: 1 addition & 1 deletion examples/inverse/mixed_norm_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
t = 0.083
tidx = evoked.time_as_index(t).item()
for di, dip in enumerate(dipoles, 1):
print(f"Dipole #{di} GOF at {1000 * t:0.1f} ms: " f"{float(dip.gof[tidx]):0.1f}%")
print(f"Dipole #{di} GOF at {1000 * t:0.1f} ms: {float(dip.gof[tidx]):0.1f}%")

# %%
# Plot dipole activations
Expand Down
6 changes: 2 additions & 4 deletions mne/_fiff/meas_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3205,9 +3205,7 @@ def create_info(ch_names, sfreq, ch_types="misc", verbose=None):
_validate_type(ch_name, "str", "each entry in ch_names")
_validate_type(ch_type, "str", "each entry in ch_types")
if ch_type not in ch_types_dict:
raise KeyError(
f"kind must be one of {list(ch_types_dict)}, " f"not {ch_type}"
)
raise KeyError(f"kind must be one of {list(ch_types_dict)}, not {ch_type}")
this_ch_dict = ch_types_dict[ch_type]
kind = this_ch_dict["kind"]
# handle chpi, where kind is a *list* of FIFF constants:
Expand Down Expand Up @@ -3352,7 +3350,7 @@ def _force_update_info(info_base, info_target):
all_infos = np.hstack([info_base, info_target])
for ii in all_infos:
if not isinstance(ii, Info):
raise ValueError("Inputs must be of type Info. " f"Found type {type(ii)}")
raise ValueError(f"Inputs must be of type Info. Found type {type(ii)}")
for key, val in info_base.items():
if key in exclude_keys:
continue
Expand Down
4 changes: 2 additions & 2 deletions mne/_fiff/proj.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ def plot_projs_topomap(
_projs.remove(_proj)
if len(_projs) == 0:
raise ValueError(
"Nothing to plot (no projectors for channel " f"type {ch_type})."
f"Nothing to plot (no projectors for channel type {ch_type})."
)
# now we have non-empty _projs list with correct channel type(s)
from ..viz.topomap import plot_projs_topomap
Expand Down Expand Up @@ -1100,7 +1100,7 @@ def _has_eeg_average_ref_proj(
missing = [name for name in want_names if name not in found_names]
if missing:
if found_names: # found some but not all: warn
warn(f"Incomplete {ch_type} projector, " f"missing channel(s) {missing}")
warn(f"Incomplete {ch_type} projector, missing channel(s) {missing}")
return False
return True

Expand Down
2 changes: 1 addition & 1 deletion mne/_fiff/tests/test_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_constants(tmp_path):
fname = "fiff.zip"
dest = tmp_path / fname
pooch.retrieve(
url="https://codeload.github.com/" f"{REPO}/fiff-constants/zip/{COMMIT}",
url=f"https://codeload.github.com/{REPO}/fiff-constants/zip/{COMMIT}",
path=tmp_path,
fname=fname,
known_hash=None,
Expand Down
4 changes: 2 additions & 2 deletions mne/_fiff/write.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def _get_split_size(split_size):
if isinstance(split_size, str):
exp = dict(MB=20, GB=30).get(split_size[-2:], None)
if exp is None:
raise ValueError("split_size has to end with either" '"MB" or "GB"')
raise ValueError('split_size has to end with either "MB" or "GB"')
split_size = int(float(split_size[:-2]) * 2**exp)

if split_size > 2147483648:
Expand Down Expand Up @@ -77,7 +77,7 @@ def write_int(fid, kind, data):
max_val = data.max() if data.size > 0 else 0
if max_val > INT32_MAX:
raise TypeError(
f"Value {max_val} exceeds maximum allowed ({INT32_MAX}) for " f"tag {kind}"
f"Value {max_val} exceeds maximum allowed ({INT32_MAX}) for tag {kind}"
)
data = data.astype(">i4").T
_write(fid, data, kind, data_size, FIFF.FIFFT_INT, ">i4")
Expand Down
2 changes: 1 addition & 1 deletion mne/bem.py
Original file line number Diff line number Diff line change
Expand Up @@ -1026,7 +1026,7 @@ def get_fitting_dig(info, dig_kinds="auto", exclude_frontal=True, verbose=None):
_validate_type(info, "info")
if info["dig"] is None:
raise RuntimeError(
"Cannot fit headshape without digitization " ', info["dig"] is None'
'Cannot fit headshape without digitization, info["dig"] is None'
)
if isinstance(dig_kinds, str):
if dig_kinds == "auto":
Expand Down
10 changes: 4 additions & 6 deletions mne/channels/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -1902,7 +1902,7 @@ def combine_channels(
# Instantiate channel info and data
new_ch_names, new_ch_types, new_data = [], [], []
if not isinstance(keep_stim, bool):
raise TypeError('"keep_stim" must be of type bool, not ' f"{type(keep_stim)}.")
raise TypeError(f'"keep_stim" must be of type bool, not {type(keep_stim)}.')
if keep_stim:
stim_ch_idx = list(pick_types(inst.info, meg=False, stim=True))
if stim_ch_idx:
Expand All @@ -1915,7 +1915,7 @@ def combine_channels(
# Get indices of bad channels
ch_idx_bad = []
if not isinstance(drop_bad, bool):
raise TypeError('"drop_bad" must be of type bool, not ' f"{type(drop_bad)}.")
raise TypeError(f'"drop_bad" must be of type bool, not {type(drop_bad)}.')
if drop_bad and inst.info["bads"]:
ch_idx_bad = pick_channels(ch_names, inst.info["bads"])

Expand All @@ -1937,7 +1937,7 @@ def combine_channels(
this_picks = [idx for idx in this_picks if idx not in ch_idx_bad]
if these_bads:
logger.info(
"Dropped the following channels in group " f"{this_group}: {these_bads}"
f"Dropped the following channels in group {this_group}: {these_bads}"
)
# Check if combining less than 2 channel
if len(set(this_picks)) < 2:
Expand Down Expand Up @@ -2130,9 +2130,7 @@ def read_vectorview_selection(name, fname=None, info=None, verbose=None):
# get the name of the selection in the file
pos = line.find(":")
if pos < 0:
logger.info(
'":" delimiter not found in selections file, ' "skipping line"
)
logger.info('":" delimiter not found in selections file, skipping line')
continue
sel_name_file = line[:pos]
# search for substring match with name provided
Expand Down
4 changes: 2 additions & 2 deletions mne/channels/tests/test_montage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1976,7 +1976,7 @@ def test_montage_add_fiducials():

# check that adding MNI fiducials fails because we're in MRI
with pytest.raises(
RuntimeError, match="Montage should be in the " '"mni_tal" coordinate frame'
RuntimeError, match='Montage should be in the "mni_tal" coordinate frame'
):
montage.add_mni_fiducials(subjects_dir=subjects_dir)

Expand All @@ -1991,7 +1991,7 @@ def test_montage_add_fiducials():
# which is the FreeSurfer RAS
montage = make_dig_montage(ch_pos=test_ch_pos, coord_frame="mni_tal")
with pytest.raises(
RuntimeError, match="Montage should be in the " '"mri" coordinate frame'
RuntimeError, match='Montage should be in the "mri" coordinate frame'
):
montage.add_estimated_fiducials(subject=subject, subjects_dir=subjects_dir)

Expand Down
2 changes: 1 addition & 1 deletion mne/commands/mne_coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def run():
type=str,
default=None,
dest="interaction",
help='Interaction style to use, can be "trackball" or ' '"terrain".',
help='Interaction style to use, can be "trackball" or "terrain".',
)
_add_verbose_flag(parser)

Expand Down
6 changes: 3 additions & 3 deletions mne/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def _check_pyqtgraph(request):
qt_version, api = _check_qt_version(return_api=True)
if (not qt_version) or _compare_version(qt_version, "<", "5.12"):
pytest.skip(
f"Qt API {api} has version {qt_version} " f"but pyqtgraph needs >= 5.12!"
f"Qt API {api} has version {qt_version} but pyqtgraph needs >= 5.12!"
)
try:
import mne_qt_browser # noqa: F401
Expand All @@ -525,10 +525,10 @@ def _check_pyqtgraph(request):
f_name = request.function.__name__
if lower_2_0 and m_name in pre_2_0_skip_modules:
pytest.skip(
f'Test-Module "{m_name}" was skipped for' f" mne-qt-browser < 0.2.0"
f'Test-Module "{m_name}" was skipped for mne-qt-browser < 0.2.0'
)
elif lower_2_0 and f_name in pre_2_0_skip_funcs:
pytest.skip(f'Test "{f_name}" was skipped for ' f"mne-qt-browser < 0.2.0")
pytest.skip(f'Test "{f_name}" was skipped for mne-qt-browser < 0.2.0')
except Exception:
pytest.skip("Requires mne_qt_browser")
else:
Expand Down
2 changes: 1 addition & 1 deletion mne/coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1905,7 +1905,7 @@ def _orig_hsp_point_distance(self):
def _log_dig_mri_distance(self, prefix):
errs_nearest = self.compute_dig_mri_distances()
logger.info(
f"{prefix} median distance: " f"{np.median(errs_nearest * 1000):6.2f} mm"
f"{prefix} median distance: {np.median(errs_nearest * 1000):6.2f} mm"
)

@property
Expand Down
6 changes: 2 additions & 4 deletions mne/decoding/csp.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,11 @@ def __init__(
if transform_into == "average_power":
if log is not None and not isinstance(log, bool):
raise ValueError(
"log must be a boolean if transform_into == " '"average_power".'
'log must be a boolean if transform_into == "average_power".'
)
else:
if log is not None:
raise ValueError(
"log must be a None if transform_into == " '"csp_space".'
)
raise ValueError('log must be a None if transform_into == "csp_space".')
self.log = log

_validate_type(norm_trace, bool, "norm_trace")
Expand Down
8 changes: 4 additions & 4 deletions mne/decoding/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,14 @@ def __init__(self, info=None, scalings=None, with_mean=True, with_std=True):

if not (scalings is None or isinstance(scalings, (dict, str))):
raise ValueError(
"scalings type should be dict, str, or None, " f"got {type(scalings)}"
f"scalings type should be dict, str, or None, got {type(scalings)}"
)
if isinstance(scalings, str):
_check_option("scalings", scalings, ["mean", "median"])
if scalings is None or isinstance(scalings, dict):
if info is None:
raise ValueError(
'Need to specify "info" if scalings is' f"{type(scalings)}"
f'Need to specify "info" if scalings is {type(scalings)}'
)
self._scaler = _ConstantScaler(info, scalings, self.with_std)
elif scalings == "mean":
Expand Down Expand Up @@ -339,7 +339,7 @@ def inverse_transform(self, X):
X = np.asarray(X)
if X.ndim not in (2, 3):
raise ValueError(
"X should be of 2 or 3 dimensions but has shape " f"{X.shape}"
f"X should be of 2 or 3 dimensions but has shape {X.shape}"
)
return X.reshape(X.shape[:-1] + self.features_shape_)

Expand Down Expand Up @@ -642,7 +642,7 @@ def __init__(self, estimator, average=False):

if not isinstance(average, bool):
raise ValueError(
"average parameter must be of bool type, got " f"{type(bool)} instead"
f"average parameter must be of bool type, got {type(bool)} instead"
)

self.estimator = estimator
Expand Down
4 changes: 2 additions & 2 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ def __init__(
reject_tmin = self.tmin
elif reject_tmin < tmin:
raise ValueError(
f"reject_tmin needs to be None or >= tmin " f"(got {reject_tmin})"
f"reject_tmin needs to be None or >= tmin (got {reject_tmin})"
)

if reject_tmax is not None:
Expand All @@ -632,7 +632,7 @@ def __init__(
reject_tmax = self.tmax
elif reject_tmax > tmax:
raise ValueError(
f"reject_tmax needs to be None or <= tmax " f"(got {reject_tmax})"
f"reject_tmax needs to be None or <= tmax (got {reject_tmax})"
)

if (reject_tmin is not None) and (reject_tmax is not None):
Expand Down
2 changes: 1 addition & 1 deletion mne/evoked.py
Original file line number Diff line number Diff line change
Expand Up @@ -1769,7 +1769,7 @@ def _read_evoked(fname, condition=None, kind="average", allow_maxshield=False):
# find string-based entry
if isinstance(condition, str):
if kind not in _aspect_dict.keys():
raise ValueError('kind must be "average" or ' '"standard_error"')
raise ValueError('kind must be "average" or "standard_error"')

comments, aspect_kinds, t = _get_entries(fid, evoked_node, allow_maxshield)
goods = np.isin(comments, [condition]) & np.isin(
Expand Down
2 changes: 1 addition & 1 deletion mne/export/_egimff.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def export_evokeds_mff(fname, evoked, history=None, *, overwrite=False, verbose=
info = evoked[0].info
if np.round(info["sfreq"]) != info["sfreq"]:
raise ValueError(
"Sampling frequency must be a whole number. " f'sfreq: {info["sfreq"]}'
f'Sampling frequency must be a whole number. sfreq: {info["sfreq"]}'
)
sampling_rate = int(info["sfreq"])

Expand Down
2 changes: 1 addition & 1 deletion mne/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1668,7 +1668,7 @@ def _mt_spectrum_proc(
kind = "Detected" if line_freqs is None else "Removed"
found_freqs = (
"\n".join(
f" {freq:6.2f} : " f"{counts[freq]:4d} window{_pl(counts[freq])}"
f" {freq:6.2f} : {counts[freq]:4d} window{_pl(counts[freq])}"
for freq in sorted(counts)
)
or " None"
Expand Down
2 changes: 1 addition & 1 deletion mne/forward/_field_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def _make_surface_mapping(
raise KeyError('surf must have both "rr" and "nn"')
if "coord_frame" not in surf:
raise KeyError(
"The surface coordinate frame must be specified " 'in surf["coord_frame"]'
'The surface coordinate frame must be specified in surf["coord_frame"]'
)
_check_option("mode", mode, ["accurate", "fast"])

Expand Down
2 changes: 1 addition & 1 deletion mne/forward/_make_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def _read_coil_def_file(fname, use_registry=True):
vals = np.fromstring(line, sep=" ")
if len(vals) != 7:
raise RuntimeError(
f"Could not interpret line {p + 1} as 7 points:\n" f"{line}"
f"Could not interpret line {p + 1} as 7 points:\n{line}"
)
# Read and verify data for each integration point
w.append(vals[0])
Expand Down
6 changes: 3 additions & 3 deletions mne/gui/_coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,7 @@ def _lock_fids_changed(self, change=None):
self._forward_widget_command(locked_widgets, "set_enabled", False)
self._forward_widget_command(fits_widgets, "set_enabled", False)
self._display_message(
"Placing MRI fiducials - " f"{self._current_fiducial.upper()}"
f"Placing MRI fiducials - {self._current_fiducial.upper()}"
)

self._set_sensors_visibility(self._lock_fids)
Expand All @@ -702,7 +702,7 @@ def _current_fiducial_changed(self, change=None):
self._follow_fiducial_view()
if not self._lock_fids:
self._display_message(
"Placing MRI fiducials - " f"{self._current_fiducial.upper()}"
f"Placing MRI fiducials - {self._current_fiducial.upper()}"
)

@observe("_info_file")
Expand Down Expand Up @@ -953,7 +953,7 @@ def _omit_hsp(self):
self._update_plot("hsp")
self._update_distance_estimation()
self._display_message(
f"{n_omitted} head shape points omitted, " f"{n_remaining} remaining."
f"{n_omitted} head shape points omitted, {n_remaining} remaining."
)

def _reset_omit_hsp_filter(self):
Expand Down
2 changes: 1 addition & 1 deletion mne/inverse_sparse/mxne_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ def mixed_norm(
_check_option("alpha", alpha, ("sure",))
elif not 0.0 <= alpha < 100:
raise ValueError(
'If not equal to "sure" alpha must be in [0, 100). ' f"Got alpha = {alpha}"
f'If not equal to "sure" alpha must be in [0, 100). Got alpha = {alpha}'
)
if n_mxne_iter < 1:
raise ValueError(
Expand Down
4 changes: 1 addition & 3 deletions mne/inverse_sparse/mxne_optim.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,9 +755,7 @@ def __call__(self, x): # noqa: D105
def norm(self, z, ord=2): # noqa: A002
"""Squared L2 norm if ord == 2 and L1 norm if order == 1."""
if ord not in (1, 2):
raise ValueError(
"Only supported norm order are 1 and 2. " f"Got ord = {ord}"
)
raise ValueError(f"Only supported norm order are 1 and 2. Got ord = {ord}")
stft_norm = stft_norm1 if ord == 1 else stft_norm2
norm = 0.0
if len(self.n_coefs) > 1:
Expand Down
4 changes: 2 additions & 2 deletions mne/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1721,7 +1721,7 @@ def save(
data_test = self[0, 0][0]
if fmt == "short" and np.iscomplexobj(data_test):
raise ValueError(
'Complex data must be saved as "single" or ' '"double", not "short"'
'Complex data must be saved as "single" or "double", not "short"'
)

# check for file existence and expand `~` if present
Expand Down Expand Up @@ -3007,7 +3007,7 @@ def _write_raw_buffer(fid, buf, cals, fmt):
write_function = write_complex128
else:
raise ValueError(
'only "single" and "double" supported for ' "writing complex data"
'only "single" and "double" supported for writing complex data'
)

buf = buf / np.ravel(cals)[:, None]
Expand Down

0 comments on commit 5b1c49e

Please sign in to comment.