Skip to content

Commit 6652a16

Browse files
Enforce ruff/pyupgrade rules (UP) (#287)
* Enforce ruff/pyupgrade rule UP008 UP008 Use `super()` instead of `super(__class__, self)` * Enforce ruff/pyupgrade rule UP032 UP032 Use f-string instead of `format` call * Enforce ruff/pyupgrade rule UP034 UP034 Avoid extraneous parentheses * Enforce ruff/pyupgrade rule UP039 UP039 Unnecessary parentheses after class definition * Enforce ruff/pyupgrade UP015 UP015 Unnecessary open mode parameters
1 parent 2c4cffe commit 6652a16

13 files changed

Lines changed: 78 additions & 105 deletions

File tree

bin/create_iods_modules.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,9 @@ def _create_modules(directory):
105105
except IndexError:
106106
raise ValueError('Path to directory must be provided.')
107107
if not os.path.exists(directory):
108-
raise OSError('Path does not exist: "{}"'.format(directory))
108+
raise OSError(f'Path does not exist: "{directory}"')
109109
if not os.path.isdir(directory):
110-
raise OSError('Path is not a directory: "{}"'.format(directory))
110+
raise OSError(f'Path is not a directory: "{directory}"')
111111

112112
now = datetime.datetime.now()
113113
current_date = datetime.datetime.date(now).strftime('%Y-%m-%d')
@@ -127,13 +127,11 @@ def _create_modules(directory):
127127
fp.write('\n\n')
128128
iods_formatted = _dump_json(iods).replace('null', 'None')
129129
fp.write(
130-
'IOD_MODULE_MAP: Dict[str, List[Dict[str, str]]] = {}'.format(
131-
iods_formatted
132-
)
130+
f'IOD_MODULE_MAP: Dict[str, List[Dict[str, str]]] = {iods_formatted}'
133131
)
134132
fp.write('\n\n')
135133
sop_to_iods_formatted = _dump_json(sop_to_iods).replace('null', 'None')
136-
fp.write('SOP_CLASS_UID_IOD_KEY_MAP = {}'.format(sop_to_iods_formatted))
134+
fp.write(f'SOP_CLASS_UID_IOD_KEY_MAP = {sop_to_iods_formatted}')
137135

138136
modules = _create_modules(directory)
139137
modules_docstr = '\n'.join([
@@ -148,7 +146,5 @@ def _create_modules(directory):
148146
fp.write('\n\n')
149147
modules_formatted = _dump_json(modules).replace('null', 'None')
150148
fp.write(
151-
'MODULE_ATTRIBUTE_MAP: Dict[str, List[Dict[str, Union[str, Sequence[str]]]]] = {}'.format( # noqa: E501
152-
modules_formatted
153-
)
149+
f'MODULE_ATTRIBUTE_MAP: Dict[str, List[Dict[str, Union[str, Sequence[str]]]]] = {modules_formatted}' # noqa: E501
154150
)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
def get_version():
1313
version_filepath = Path('src', 'highdicom', 'version.py')
14-
with open(version_filepath, 'rt', encoding='utf8') as f:
14+
with open(version_filepath, encoding='utf8') as f:
1515
version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)
1616
return version
1717

src/highdicom/base.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,7 @@ def __init__(
153153
self.file_meta.ImplementationClassUID = UID(
154154
'1.2.826.0.1.3680043.9.7433.1.1'
155155
)
156-
self.file_meta.ImplementationVersionName = 'highdicom{}'.format(
157-
__version__
158-
)
156+
self.file_meta.ImplementationVersionName = f'highdicom{__version__}'
159157
self.fix_meta_info(enforce_standard=True)
160158
with BytesIO() as fp:
161159
write_file_meta_info(fp, self.file_meta, enforce_standard=True)
@@ -269,9 +267,9 @@ def _copy_attribute(
269267
raise ValueError('No tag not found for keyword "{keyword}".')
270268
try:
271269
data_element = dataset[tag]
272-
logger.debug('copied attribute "{}"'.format(keyword))
270+
logger.debug(f'copied attribute "{keyword}"')
273271
except KeyError:
274-
logger.debug('skipped attribute "{}"'.format(keyword))
272+
logger.debug(f'skipped attribute "{keyword}"')
275273
return
276274
self.add(data_element)
277275

@@ -297,9 +295,8 @@ def _copy_root_attributes_of_module(
297295
from highdicom._iods import IOD_MODULE_MAP, SOP_CLASS_UID_IOD_KEY_MAP
298296
from highdicom._modules import MODULE_ATTRIBUTE_MAP
299297
logger.info(
300-
'copy {}-related attributes from dataset "{}"'.format(
301-
ie, dataset.SOPInstanceUID
302-
)
298+
f'copy {ie}-related attributes from '
299+
f'dataset "{dataset.SOPInstanceUID}"'
303300
)
304301
iod_key = SOP_CLASS_UID_IOD_KEY_MAP[dataset.SOPClassUID]
305302
for module_item in IOD_MODULE_MAP[iod_key]:

src/highdicom/content.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,7 @@ def __eq__(self, other: Any) -> bool:
508508
if not isinstance(other, self.__class__):
509509
raise TypeError(
510510
'Can only compare image position between instances of '
511-
'class "{}".'.format(self.__class__.__name__)
511+
f'class "{self.__class__.__name__}".'
512512
)
513513
if hasattr(self[0], 'ImagePositionPatient'):
514514
return np.array_equal(
@@ -648,7 +648,7 @@ def __eq__(self, other: Any) -> bool:
648648
if not isinstance(other, self.__class__):
649649
raise TypeError(
650650
'Can only compare orientation between instances of '
651-
'class "{}".'.format(self.__class__.__name__)
651+
f'class "{self.__class__.__name__}".'
652652
)
653653
if hasattr(self[0], 'ImageOrientationPatient'):
654654
if not hasattr(other[0], 'ImageOrientationPatient'):

src/highdicom/io.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,9 +282,8 @@ def __exit__(self, except_type, except_value, except_trace) -> None:
282282
pass
283283
if except_value:
284284
sys.stderr.write(
285-
'Error while accessing file "{}":\n{}'.format(
286-
self._filename, str(except_value)
287-
)
285+
f'Error while accessing file "{self._filename}":\n'
286+
f'{except_value}'
288287
)
289288
for tb in traceback.format_tb(except_trace):
290289
sys.stderr.write(tb)

src/highdicom/pm/sop.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,7 @@ def __init__(
739739
frame_content_item.DimensionIndexValues = [
740740
int(
741741
np.where(
742-
(dimension_position_values[idx] == pos)
742+
dimension_position_values[idx] == pos
743743
)[0][0] + 1
744744
)
745745
for idx, pos in enumerate(plane_position_values[i])

src/highdicom/seg/sop.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1637,7 +1637,7 @@ def __init__(
16371637
self.MaximumFractionalValue = max_fractional_value
16381638
else:
16391639
raise ValueError(
1640-
'Unknown segmentation type "{}"'.format(segmentation_type)
1640+
f'Unknown segmentation type "{segmentation_type}"'
16411641
)
16421642

16431643
self.BitsStored = self.BitsAllocated
@@ -2831,7 +2831,7 @@ def _get_dimension_index_values(
28312831
index_values = [
28322832
int(
28332833
np.where(
2834-
(unique_dimension_values[idx] == pos)
2834+
unique_dimension_values[idx] == pos
28352835
)[0][0] + 1
28362836
)
28372837
for idx, pos in enumerate(plane_position_value)

src/highdicom/sr/coding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __init__(
3232
version of coding scheme
3333
3434
"""
35-
super(CodedConcept, self).__init__()
35+
super().__init__()
3636
if len(value) > 16:
3737
if value.startswith('urn') or '://' in value:
3838
self.URNCodeValue = str(value)

src/highdicom/sr/templates.py

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,20 +1573,16 @@ def __init__(
15731573
PersonObserverIdentifyingAttributes):
15741574
raise TypeError(
15751575
'Observer identifying attributes must have '
1576-
'type {} for observer type "{}".'.format(
1577-
PersonObserverIdentifyingAttributes.__name__,
1578-
observer_type.meaning
1579-
)
1576+
f'type {PersonObserverIdentifyingAttributes.__name__} '
1577+
f'for observer type "{observer_type.meaning}".'
15801578
)
15811579
elif observer_type == codes.cid270.Device:
15821580
if not isinstance(observer_identifying_attributes,
15831581
DeviceObserverIdentifyingAttributes):
15841582
raise TypeError(
15851583
'Observer identifying attributes must have '
1586-
'type {} for observer type "{}".'.format(
1587-
DeviceObserverIdentifyingAttributes.__name__,
1588-
observer_type.meaning,
1589-
)
1584+
f'type {DeviceObserverIdentifyingAttributes.__name__} '
1585+
f'for observer type "{observer_type.meaning}".'
15901586
)
15911587
else:
15921588
raise ValueError(
@@ -2184,26 +2180,21 @@ def __init__(
21842180
if not isinstance(observer_person_context, ObserverContext):
21852181
raise TypeError(
21862182
'Argument "observer_person_context" must '
2187-
'have type {}'.format(
2188-
ObserverContext.__name__
2189-
)
2183+
f'have type {ObserverContext.__name__}'
21902184
)
21912185
self.extend(observer_person_context)
21922186
if observer_device_context is not None:
21932187
if not isinstance(observer_device_context, ObserverContext):
21942188
raise TypeError(
21952189
'Argument "observer_device_context" must '
2196-
'have type {}'.format(
2197-
ObserverContext.__name__
2198-
)
2190+
f'have type {ObserverContext.__name__}'
21992191
)
22002192
self.extend(observer_device_context)
22012193
if subject_context is not None:
22022194
if not isinstance(subject_context, SubjectContext):
22032195
raise TypeError(
2204-
'Argument "subject_context" must have type {}'.format(
2205-
SubjectContext.__name__
2206-
)
2196+
f'Argument "subject_context" must have '
2197+
f'type {SubjectContext.__name__}'
22072198
)
22082199
self.extend(subject_context)
22092200

@@ -3495,10 +3486,7 @@ def from_sequence(
34953486
Content Sequence containing root CONTAINER SR Content Item
34963487
34973488
"""
3498-
instance = super(
3499-
PlanarROIMeasurementsAndQualitativeEvaluations,
3500-
cls
3501-
).from_sequence(sequence)
3489+
instance = super().from_sequence(sequence)
35023490
instance.__class__ = PlanarROIMeasurementsAndQualitativeEvaluations
35033491
return cast(PlanarROIMeasurementsAndQualitativeEvaluations, instance)
35043492

@@ -3773,10 +3761,7 @@ def from_sequence(
37733761
Content Sequence containing root CONTAINER SR Content Item
37743762
37753763
"""
3776-
instance = super(
3777-
VolumetricROIMeasurementsAndQualitativeEvaluations,
3778-
cls
3779-
).from_sequence(sequence)
3764+
instance = super().from_sequence(sequence)
37803765
instance.__class__ = VolumetricROIMeasurementsAndQualitativeEvaluations
37813766
return cast(
37823767
VolumetricROIMeasurementsAndQualitativeEvaluations,

0 commit comments

Comments
 (0)