Skip to content

Commit bfcceb7

Browse files
committed
MAINT: use f-strings everywhere (larray-project/larray#854)
1 parent e1c970d commit bfcceb7

File tree

11 files changed

+63
-67
lines changed

11 files changed

+63
-67
lines changed

doc/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# sys.path.insert(0, os.path.abspath('../../'))
1818

1919
import larray_editor
20-
print("larray-editor: {}, {}".format(larray_editor.__version__, larray_editor.__file__))
20+
print(f"larray-editor: {larray_editor.__version__}, {larray_editor.__file__}")
2121

2222
# -- Project information -----------------------------------------------------
2323

larray_editor/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ def compare(*args, **kwargs):
287287
if names is None:
288288
def get_name(i, obj, depth=0):
289289
obj_names = find_names(obj, depth=depth + 1)
290-
return obj_names[0] if obj_names else '%s %d' % (default_name, i)
290+
return obj_names[0] if obj_names else f'{default_name} {i:d}'
291291

292292
# depth + 2 because of the list comprehension
293293
names = [get_name(i, a, depth=depth + 2) for i, a in enumerate(args)]

larray_editor/arrayadapter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def get_adapter(data, bg_value):
2727
return None
2828
data_type = type(data)
2929
if data_type not in REGISTERED_ADAPTERS:
30-
raise TypeError("No Adapter implemented for data with type {}".format(data_type))
30+
raise TypeError(f"No Adapter implemented for data with type {data_type}")
3131
adapter_cls = REGISTERED_ADAPTERS[data_type]
3232
return adapter_cls(data, bg_value)
3333

@@ -52,7 +52,7 @@ def data(self):
5252

5353
@data.setter
5454
def data(self, original_data):
55-
assert original_data is not None, "{} does not accept None as input data".format(self.__class__)
55+
assert original_data is not None, f"{self.__class__} does not accept None as input data"
5656
self._original_data = self.prepare_data(original_data)
5757

5858
@property

larray_editor/arraymodel.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ def reset(self):
111111
self.endResetModel()
112112
if logger.isEnabledFor(logging.DEBUG):
113113
caller = stack()[1]
114-
logger.debug("model {} has been reset after call of {} from module {} at line {}".format(self.__class__,
115-
caller.function, basename(caller.filename), caller.lineno))
114+
logger.debug(f"model {self.__class__} has been reset after call of {caller.function} from module "
115+
f"{basename(caller.filename)} at line {caller.lineno}")
116116

117117

118118
class AxesArrayModel(AbstractArrayModel):
@@ -303,7 +303,7 @@ def _set_data(self, data):
303303
dtn = dtype.name
304304
if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \
305305
and not dtn.startswith('unicode'):
306-
QMessageBox.critical(self.dialog, "Error", "{} arrays are currently not supported".format(dtn))
306+
QMessageBox.critical(self.dialog, "Error", f"{dtn} arrays are currently not supported")
307307
return
308308
# for complex numbers, shading will be based on absolute value
309309
# but for all other types it will be the real part
@@ -356,8 +356,7 @@ def set_bg_gradient(self, bg_gradient, reset=True):
356356

357357
def set_bg_value(self, bg_value, reset=True):
358358
if bg_value is not None and not (isinstance(bg_value, np.ndarray) and bg_value.shape == self._data.shape):
359-
raise ValueError("Expected None or 2D Numpy ndarray with shape {} for `bg_value` argument"
360-
.format(self._data.shape))
359+
raise ValueError(f"Expected None or 2D Numpy ndarray with shape {self._data.shape} for `bg_value` argument")
361360
self.bg_value = bg_value
362361
if reset:
363362
self.reset()
@@ -428,7 +427,7 @@ def data(self, index, role=Qt.DisplayRole):
428427
v = self.bg_value[i, j]
429428
return self.bg_gradient[v]
430429
# elif role == Qt.ToolTipRole:
431-
# return "{}\n{}".format(repr(value),self.get_labels(index))
430+
# return f"{repr(value)}\n{self.get_labels(index)}"
432431
return None
433432

434433
def get_values(self, left=0, top=0, right=None, bottom=None, sample=False):
@@ -478,10 +477,10 @@ def convert_values(self, values):
478477
for i, v in enumerate(values.flat):
479478
res.flat[i] = self.convert_value(v)
480479
except ValueError as e:
481-
QMessageBox.critical(self.dialog, "Error", "Value error: %s" % str(e))
480+
QMessageBox.critical(self.dialog, "Error", f"Value error: {str(e)}")
482481
return None
483482
except OverflowError as e:
484-
QMessageBox.critical(self.dialog, "Error", "Overflow error: %s" % e.message)
483+
QMessageBox.critical(self.dialog, "Error", f"Overflow error: {e.message}")
485484
return None
486485
return res
487486

larray_editor/arraywidget.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,10 @@ def __init__(self, parent, model, hpos, vpos):
9999

100100
# set position
101101
if not (hpos == LEFT or hpos == RIGHT):
102-
raise TypeError("Value of hpos must be {} or {}".format(LEFT, RIGHT))
102+
raise TypeError(f"Value of hpos must be {LEFT} or {RIGHT}")
103103
self.hpos = hpos
104104
if not (vpos == TOP or vpos == BOTTOM):
105-
raise TypeError("Value of vpos must be {} or {}".format(TOP, BOTTOM))
105+
raise TypeError(f"Value of vpos must be {TOP} or {BOTTOM}")
106106
self.vpos = vpos
107107

108108
# set selection mode
@@ -187,8 +187,8 @@ class AxesView(AbstractView):
187187
def __init__(self, parent, model):
188188
# check model
189189
if not isinstance(model, AxesArrayModel):
190-
raise TypeError("Expected model of type {}. Received {} instead"
191-
.format(AxesArrayModel.__name__, type(model).__name__))
190+
raise TypeError(f"Expected model of type {AxesArrayModel.__name__}. "
191+
f"Received {type(model).__name__} instead")
192192
AbstractView.__init__(self, parent, model, LEFT, TOP)
193193

194194
def selectAll(self):
@@ -201,8 +201,8 @@ class LabelsView(AbstractView):
201201
def __init__(self, parent, model, hpos, vpos):
202202
# check model
203203
if not isinstance(model, LabelsArrayModel):
204-
raise TypeError("Expected model of type {}. Received {} instead"
205-
.format(LabelsArrayModel.__name__, type(model).__name__))
204+
raise TypeError(f"Expected model of type {LabelsArrayModel.__name__}. "
205+
f"Received {type(model).__name__} instead")
206206
AbstractView.__init__(self, parent, model, hpos, vpos)
207207

208208

@@ -236,11 +236,11 @@ def createEditor(self, parent, option, index):
236236
elif value is not np.ma.masked:
237237
minvalue, maxvalue = self.minvalue, self.maxvalue
238238
if minvalue is not None and maxvalue is not None:
239-
msg = "value must be between %s and %s" % (minvalue, maxvalue)
239+
msg = f"value must be between {minvalue} and {maxvalue}"
240240
elif minvalue is not None:
241-
msg = "value must be >= %s" % minvalue
241+
msg = f"value must be >= {minvalue}"
242242
elif maxvalue is not None:
243-
msg = "value must be <= %s" % maxvalue
243+
msg = f"value must be <= {maxvalue}"
244244
else:
245245
msg = None
246246

@@ -293,8 +293,8 @@ class DataView(AbstractView):
293293
def __init__(self, parent, model):
294294
# check model
295295
if not isinstance(model, DataArrayModel):
296-
raise TypeError("Expected model of type {}. Received {} instead"
297-
.format(DataArrayModel.__name__, type(model).__name__))
296+
raise TypeError(f"Expected model of type {DataArrayModel.__name__}. "
297+
f"Received {type(model).__name__} instead")
298298
AbstractView.__init__(self, parent, model, RIGHT, BOTTOM)
299299

300300
self.context_menu = self.setup_context_menu()

larray_editor/combo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def __getitem__(self, key):
3636
return [self.item(i) for i in range(start, stop, step)]
3737
else:
3838
if key >= self.rowCount():
39-
raise IndexError("index %d is out of range" % key)
39+
raise IndexError(f"index {key} is out of range")
4040
return self.item(key)
4141

4242
def __len__(self):
@@ -261,7 +261,7 @@ def __init__(self):
261261

262262
combo = FilterComboBox(self)
263263
for i in range(20):
264-
combo.addItem('Item %s' % i)
264+
combo.addItem(f'Item {i}')
265265
layout.addWidget(combo)
266266

267267
app = QtWidgets.QApplication(sys.argv)

larray_editor/commands.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def __init__(self, editor, target, changes):
4949
text_command = self.get_description(target, changes)
5050
self.setText(text_command)
5151
if logger.isEnabledFor(logging.DEBUG):
52-
logger.debug("Edit command pushed: {}".format(text_command))
52+
logger.debug(f"Edit command pushed: {text_command}")
5353

5454
def undo(self):
5555
for change in self.changes:
@@ -83,12 +83,12 @@ class EditSessionArrayCommand(EditArrayCommand):
8383
"""
8484
def get_description(self, target, changes):
8585
if len(changes) == 1:
86-
return "Editing Cell {} of {}".format(changes[0].key, target)
86+
return f"Editing Cell {changes[0].key} of {target}"
8787
else:
88-
return "Pasting {} Cells in {}".format(len(changes), target)
88+
return f"Pasting {len(changes)} Cells in {target}"
8989

9090
def apply_change(self, key, new_value):
91-
self.editor.kernel.shell.run_cell("{}[{}] = {}".format(self.target, key, new_value))
91+
self.editor.kernel.shell.run_cell(f"{self.target}[{key}] = {new_value}")
9292

9393

9494
class EditCurrentArrayCommand(EditArrayCommand):
@@ -106,9 +106,9 @@ class EditCurrentArrayCommand(EditArrayCommand):
106106
"""
107107
def get_description(self, target, changes):
108108
if len(changes) == 1:
109-
return "Editing Cell {}".format(changes[0].key)
109+
return f"Editing Cell {changes[0].key}"
110110
else:
111-
return "Pasting {} Cells".format(len(changes))
111+
return f"Pasting {len(changes)} Cells"
112112

113113
def apply_change(self, key, new_value):
114114
self.target[key] = new_value

larray_editor/comparator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ def _setup_and_check(self, widget, data, title, readonly, **kwargs):
193193
* names: list of str
194194
"""
195195
arrays = [la.asarray(array) for array in data if isinstance(array, DISPLAY_IN_GRID)]
196-
names = kwargs.get('names', ["Array{}".format(i) for i in range(len(arrays))])
196+
names = kwargs.get('names', [f"Array{i}" for i in range(len(arrays))])
197197

198198
layout = QVBoxLayout()
199199
widget.setLayout(layout)
@@ -239,7 +239,7 @@ def _setup_and_check(self, widget, data, title, readonly, **kwargs):
239239
* colors: str
240240
"""
241241
sessions = data
242-
names = kwargs.get('names', ["Session{}".format(i) for i in range(len(sessions))])
242+
names = kwargs.get('names', [f"Session{i}" for i in range(len(sessions))])
243243

244244
assert all(isinstance(s, la.Session) for s in sessions)
245245
self.sessions = sessions

larray_editor/editor.py

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@ def setup_and_check(self, data, title='', readonly=False, caller_info=None, **kw
116116

117117
# permanently display caller info in the status bar
118118
if caller_info is not None:
119-
caller_info = 'launched from file {} at line {}'.format(caller_info.filename, caller_info.lineno)
119+
caller_info = f'launched from file {caller_info.filename} at line {caller_info.lineno}'
120120
self.statusBar().addPermanentWidget(QLabel(caller_info))
121121
# display welcome message
122-
self.statusBar().showMessage("Welcome to the {}".format(self.name), 4000)
122+
self.statusBar().showMessage(f"Welcome to the {self.name}", 4000)
123123

124124
# set central widget
125125
widget = QWidget()
@@ -224,12 +224,12 @@ def _report_issue(*args, **kwargs):
224224
## Version and main components
225225
* Python {python} on {system} {bitness:d}bits
226226
"""
227-
issue_template += "* {package} {{{package}}}\n".format(package=package)
227+
issue_template += f"* {package} {{{package}}}\n"
228228
for dep in dependencies[package]:
229-
issue_template += "* {dep} {{{dep}}}\n".format(dep=dep)
229+
issue_template += f"* {dep} {{{dep}}}\n"
230230
issue_template = issue_template.format(**versions)
231231

232-
url = QUrl(urls['new_issue_{}'.format(package)])
232+
url = QUrl(urls[f'new_issue_{package}'])
233233
if PYQT5:
234234
from qtpy.QtCore import QUrlQuery
235235
query = QUrlQuery()
@@ -263,7 +263,7 @@ def about(self):
263263
"""
264264
for dep in dependencies['editor']:
265265
if kwargs[dep] != 'N/A':
266-
message += "<li>{dep} {{{dep}}}</li>\n".format(dep=dep)
266+
message += f"<li>{dep} {{{dep}}}</li>\n"
267267
message += "</ul>"
268268
QMessageBox.about(self, _("About LArray Editor"), message.format(**kwargs))
269269

@@ -276,14 +276,14 @@ def _update_title(self, title, array, name):
276276
# current file (if not None)
277277
if isinstance(array, la.Array):
278278
# array info
279-
shape = ['{} ({})'.format(display_name, len(axis))
279+
shape = [f'{display_name} ({len(axis)})'
280280
for display_name, axis in zip(array.axes.display_names, array.axes)]
281281
else:
282282
# if it's not an Array, it must be a Numpy ndarray
283283
assert isinstance(array, np.ndarray)
284284
shape = [str(length) for length in array.shape]
285285
# name + shape + dtype
286-
array_info = ' x '.join(shape) + ' [{}]'.format(dtype)
286+
array_info = ' x '.join(shape) + f' [{dtype}]'
287287
if name:
288288
title += [name + ': ' + array_info]
289289
else:
@@ -306,7 +306,7 @@ def save_widgets_state_and_geometry(self):
306306
settings.setValue('geometry', self.saveGeometry())
307307
settings.setValue('state', self.saveState())
308308
for widget_name, widget in self.widget_state_settings.items():
309-
settings.setValue('state/{}'.format(widget_name), widget.saveState())
309+
settings.setValue(f'state/{widget_name}', widget.saveState())
310310
settings.endGroup()
311311

312312
def restore_widgets_state_and_geometry(self):
@@ -319,7 +319,7 @@ def restore_widgets_state_and_geometry(self):
319319
if state:
320320
self.restoreState(state)
321321
for widget_name, widget in self.widget_state_settings.items():
322-
state = settings.value('state/{}'.format(widget_name))
322+
state = settings.value(f'state/{widget_name}')
323323
if state:
324324
widget.restoreState(state)
325325
settings.endGroup()
@@ -440,7 +440,7 @@ def void_formatter(array, *args, **kwargs):
440440
funcname = frame_summary.name
441441
filename = os.path.basename(frame_summary.filename)
442442
listitem = QListWidgetItem(stack_frame_widget)
443-
listitem.setText("{}, {}:{}".format(funcname, filename, frame_summary.lineno))
443+
listitem.setText(f"{funcname}, {filename}:{frame_summary.lineno}")
444444
# we store the frame summary object in the user data of the list
445445
listitem.setData(Qt.UserRole, frame_summary)
446446
listitem.setToolTip(frame_summary.line)
@@ -474,7 +474,7 @@ def void_formatter(array, *args, **kwargs):
474474
if os.path.isfile(data):
475475
self._open_file(data)
476476
else:
477-
QMessageBox.critical(self, "Error", "File {} could not be found".format(data))
477+
QMessageBox.critical(self, "Error", f"File {data} could not be found")
478478
self.new()
479479
elif not debug:
480480
self._push_data(data)
@@ -757,15 +757,15 @@ def update_title(self):
757757
basename = os.path.basename(self.current_file)
758758
if os.path.isdir(self.current_file):
759759
assert not name.endswith('.csv')
760-
fname = os.path.join(basename, '{}.csv'.format(name))
760+
fname = os.path.join(basename, f'{name}.csv')
761761
name = ''
762762
else:
763763
fname = basename
764764
else:
765765
fname = '<new>'
766766

767767
array = self.current_array
768-
title = ['{}{}'.format(unsaved_marker, fname)]
768+
title = [f'{unsaved_marker}{fname}']
769769
self._update_title(title, array, name)
770770

771771
def set_current_array(self, array, name):
@@ -838,8 +838,7 @@ def _load_script(self, filepath):
838838
self.ipython_cell_executed()
839839
self.recent_loaded_scripts.add(filepath)
840840
except Exception as e:
841-
QMessageBox.critical(self, "Error", "Cannot load script file {}:\n{}"
842-
.format(os.path.basename(filepath), e))
841+
QMessageBox.critical(self, "Error", f"Cannot load script file {os.path.basename(filepath)}:\n{e}")
843842

844843
def load_script(self, filepath=None):
845844
# %load add automatically the extension .py if not present in passed filename
@@ -923,12 +922,11 @@ def _save_script(self, filepath, lines, overwrite):
923922
if lines:
924923
lines = lines.replace('..', '-')
925924
else:
926-
lines = '1-{}'.format(self.kernel.shell.execution_count)
927-
self.kernel.shell.run_line_magic('save', '{} {} {}'.format(overwrite, filepath, lines))
925+
lines = f'1-{self.kernel.shell.execution_count}'
926+
self.kernel.shell.run_line_magic('save', f'{overwrite} {filepath} {lines}')
928927
self.recent_saved_scripts.add(filepath)
929928
except Exception as e:
930-
QMessageBox.critical(self, "Error", "Cannot save history as {}:\n{}"
931-
.format(os.path.basename(filepath), e))
929+
QMessageBox.critical(self, "Error", f"Cannot save history as {os.path.basename(filepath)}:\n{e}")
932930

933931
# See http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-save
934932
# for more details
@@ -1007,7 +1005,7 @@ def save_script(self):
10071005
overwrite = radio_button_overwrite.isChecked()
10081006
if overwrite and os.path.isfile(filepath):
10091007
ret = QMessageBox.warning(self, "Warning",
1010-
"File `{}` exists. Are you sure to overwrite it?".format(filepath),
1008+
f"File `{filepath}` exists. Are you sure to overwrite it?",
10111009
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
10121010
if ret == QMessageBox.Save:
10131011
self._save_script(filepath, lines, overwrite)
@@ -1043,10 +1041,9 @@ def _open_file(self, filepath: Union[str, Path]):
10431041
self._push_data(session)
10441042
self.set_current_file(current_file_name)
10451043
self.unsaved_modifications = False
1046-
self.statusBar().showMessage("Loaded: {}".format(display_name), 4000)
1044+
self.statusBar().showMessage(f"Loaded: {display_name}", 4000)
10471045
except Exception as e:
1048-
QMessageBox.critical(self, "Error", "Something went wrong during load of file(s) {}:\n{}"
1049-
.format(display_name, e))
1046+
QMessageBox.critical(self, "Error", f"Something went wrong during load of file(s) {display_name}:\n{e}")
10501047

10511048
def open_data(self):
10521049
if self._ask_to_save_if_unsaved_modifications():
@@ -1073,7 +1070,7 @@ def open_recent_file(self):
10731070
if os.path.exists(filepath):
10741071
self._open_file(filepath)
10751072
else:
1076-
QMessageBox.warning(self, "Warning", "File {} could not be found".format(filepath))
1073+
QMessageBox.warning(self, "Warning", f"File {filepath} could not be found")
10771074

10781075
def _save_data(self, filepath):
10791076
try:
@@ -1082,9 +1079,9 @@ def _save_data(self, filepath):
10821079
self.set_current_file(filepath)
10831080
self.edit_undo_stack.clear()
10841081
self.unsaved_modifications = False
1085-
self.statusBar().showMessage("Arrays saved in file {}".format(filepath), 4000)
1082+
self.statusBar().showMessage(f"Arrays saved in file {filepath}", 4000)
10861083
except Exception as e:
1087-
QMessageBox.critical(self, "Error", "Something went wrong during save in file {}:\n{}".format(filepath, e))
1084+
QMessageBox.critical(self, "Error", f"Something went wrong during save in file {filepath}:\n{e}")
10881085

10891086
def save_data(self):
10901087
"""

0 commit comments

Comments
 (0)