Skip to content

MNT: Assorted refurb suggestions #1270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions nibabel/cifti2/cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,13 +968,13 @@ def vertex_indices(self, value):
def _to_xml_element(self):
brain_model = xml.Element('BrainModel')

for key in [
for key in (
'IndexOffset',
'IndexCount',
'ModelType',
'BrainStructure',
'SurfaceNumberOfVertices',
]:
):
attr = _underscore(key)
value = getattr(self, attr)
if value is not None:
Expand Down Expand Up @@ -1157,14 +1157,14 @@ def _to_xml_element(self):
mat_ind_map = xml.Element('MatrixIndicesMap')
dims_as_strings = [str(dim) for dim in self.applies_to_matrix_dimension]
mat_ind_map.attrib['AppliesToMatrixDimension'] = ','.join(dims_as_strings)
for key in [
for key in (
'IndicesMapToDataType',
'NumberOfSeriesPoints',
'SeriesExponent',
'SeriesStart',
'SeriesStep',
'SeriesUnit',
]:
):
attr = _underscore(key)
value = getattr(self, attr)
if value is not None:
Expand Down
8 changes: 4 additions & 4 deletions nibabel/cifti2/parse_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,13 @@ def StartElementHandler(self, name, attrs):
applies_to_matrix_dimension=dimensions,
indices_map_to_data_type=attrs['IndicesMapToDataType'],
)
for key, dtype in [
for key, dtype in (
('NumberOfSeriesPoints', int),
('SeriesExponent', int),
('SeriesStart', float),
('SeriesStep', float),
('SeriesUnit', str),
]:
):
if key in attrs:
setattr(mim, _underscore(key), dtype(attrs[key]))
matrix = self.struct_state[-1]
Expand Down Expand Up @@ -366,13 +366,13 @@ def StartElementHandler(self, name, attrs):
'BrainModel element can only be a child of a MatrixIndicesMap '
'with CIFTI_INDEX_TYPE_BRAIN_MODELS type'
)
for key, dtype in [
for key, dtype in (
('IndexOffset', int),
('IndexCount', int),
('ModelType', str),
('BrainStructure', str),
('SurfaceNumberOfVertices', int),
]:
):
if key in attrs:
setattr(model, _underscore(key), dtype(attrs[key]))
if model.brain_structure not in CIFTI_BRAIN_STRUCTURES:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def proc_file(f, opts):
if (
hasattr(h, 'has_data_slope')
and (h.has_data_slope or h.has_data_intercept)
and not h.get_slope_inter() in [(1.0, 0.0), (None, None)]
and not h.get_slope_inter() in ((1.0, 0.0), (None, None))
):
row += ['@l*%.3g+%.3g' % h.get_slope_inter()]
else:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/parrec2nii.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def main():

verbose.switch = opts.verbose

if opts.origin not in ['scanner', 'fov']:
if opts.origin not in ('scanner', 'fov'):
error(f"Unrecognized value for --origin: '{opts.origin}'.", 1)
if opts.dwell_time and opts.field_strength is None:
error('Need --field-strength for dwell time calculation', 1)
Expand Down
4 changes: 2 additions & 2 deletions nibabel/cmdline/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ def table2string(table, out=None):
if item.startswith('@'):
align = item[1]
item = item[2:]
if align not in ['l', 'r', 'c', 'w']:
if align not in ('l', 'r', 'c', 'w'):
raise ValueError(f'Unknown alignment {align}. Known are l,r,c')
else:
align = 'c'

nspacesl = max(ceil((col_width[j] - len(item)) / 2.0), 0)
nspacesr = max(col_width[j] - nspacesl - len(item), 0)

if align in ['w', 'c']:
if align in ('w', 'c'):
pass
elif align == 'l':
nspacesl, nspacesr = 0, nspacesl + nspacesr
Expand Down
2 changes: 1 addition & 1 deletion nibabel/freesurfer/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def _read_volume_info(fobj):
return volume_info

volume_info['head'] = head
for key in ['valid', 'filename', 'volume', 'voxelsize', 'xras', 'yras', 'zras', 'cras']:
for key in ('valid', 'filename', 'volume', 'voxelsize', 'xras', 'yras', 'zras', 'cras'):
pair = fobj.readline().decode('utf-8').split('=')
if pair[0].strip() != key or len(pair) != 2:
raise OSError('Error parsing volume info.')
Expand Down
2 changes: 1 addition & 1 deletion nibabel/gifti/gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def _to_xml_element(self):
label = xml.SubElement(labeltable, 'Label')
label.attrib['Key'] = str(ele.key)
label.text = ele.label
for attr in ['Red', 'Green', 'Blue', 'Alpha']:
for attr in ('Red', 'Green', 'Blue', 'Alpha'):
if getattr(ele, attr.lower(), None) is not None:
label.attrib[attr] = str(getattr(ele, attr.lower()))
return labeltable
Expand Down
2 changes: 1 addition & 1 deletion nibabel/gifti/parse_gifti_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ def EndElementHandler(self, name):
self.fsm_state.pop()
self.coordsys = None

elif name in ['DataSpace', 'TransformedSpace', 'MatrixData', 'Name', 'Value', 'Data']:
elif name in ('DataSpace', 'TransformedSpace', 'MatrixData', 'Name', 'Value', 'Data'):
self.write_to = None

elif name == 'Label':
Expand Down
9 changes: 5 additions & 4 deletions nibabel/nifti1.py
Original file line number Diff line number Diff line change
Expand Up @@ -1636,10 +1636,11 @@ def set_slice_times(self, slice_times):
labels = so_recoder.value_set('label')
labels.remove('unknown')

matching_labels = []
for label in labels:
if np.all(st_order == self._slice_time_order(label, n_timed)):
matching_labels.append(label)
matching_labels = [
label
for label in labels
if np.all(st_order == self._slice_time_order(label, n_timed))
]

if not matching_labels:
raise HeaderDataError(f'slice ordering of {st_order} fits with no known scheme')
Expand Down
8 changes: 4 additions & 4 deletions nibabel/streamlines/array_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def fn_binary_op(self, value):
fn.__name__ = op
fn.__doc__ = getattr(np.ndarray, op).__doc__

for op in [
for op in (
'__add__',
'__sub__',
'__mul__',
Expand All @@ -85,14 +85,14 @@ def fn_binary_op(self, value):
'__or__',
'__and__',
'__xor__',
]:
):
_wrap(cls, op=op, inplace=False)
_wrap(cls, op=f"__i{op.strip('_')}__", inplace=True)

for op in ['__eq__', '__ne__', '__lt__', '__le__', '__gt__', '__ge__']:
for op in ('__eq__', '__ne__', '__lt__', '__le__', '__gt__', '__ge__'):
_wrap(cls, op)

for op in ['__neg__', '__abs__', '__invert__']:
for op in ('__neg__', '__abs__', '__invert__'):
_wrap(cls, op, unary=True)

return cls
Expand Down
2 changes: 1 addition & 1 deletion nibabel/viewers.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ def _on_keypress(self, event):
"""Handle mpl keypress events"""
if event.key is not None and 'escape' in event.key:
self.close()
elif event.key in ['=', '+']:
elif event.key in ('=', '+'):
# increment volume index
new_idx = min(self._data_idx[3] + 1, self.n_volumes)
self._set_volume_index(new_idx, update_slices=True)
Expand Down