Skip to content

Commit

Permalink
Enforce ruff/pyupgrade rules (UP) (#287)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
DimitriPapadopoulos authored Jun 15, 2024
1 parent 2c4cffe commit 6652a16
Show file tree
Hide file tree
Showing 13 changed files with 78 additions and 105 deletions.
14 changes: 5 additions & 9 deletions bin/create_iods_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ def _create_modules(directory):
except IndexError:
raise ValueError('Path to directory must be provided.')
if not os.path.exists(directory):
raise OSError('Path does not exist: "{}"'.format(directory))
raise OSError(f'Path does not exist: "{directory}"')
if not os.path.isdir(directory):
raise OSError('Path is not a directory: "{}"'.format(directory))
raise OSError(f'Path is not a directory: "{directory}"')

now = datetime.datetime.now()
current_date = datetime.datetime.date(now).strftime('%Y-%m-%d')
Expand All @@ -127,13 +127,11 @@ def _create_modules(directory):
fp.write('\n\n')
iods_formatted = _dump_json(iods).replace('null', 'None')
fp.write(
'IOD_MODULE_MAP: Dict[str, List[Dict[str, str]]] = {}'.format(
iods_formatted
)
f'IOD_MODULE_MAP: Dict[str, List[Dict[str, str]]] = {iods_formatted}'
)
fp.write('\n\n')
sop_to_iods_formatted = _dump_json(sop_to_iods).replace('null', 'None')
fp.write('SOP_CLASS_UID_IOD_KEY_MAP = {}'.format(sop_to_iods_formatted))
fp.write(f'SOP_CLASS_UID_IOD_KEY_MAP = {sop_to_iods_formatted}')

modules = _create_modules(directory)
modules_docstr = '\n'.join([
Expand All @@ -148,7 +146,5 @@ def _create_modules(directory):
fp.write('\n\n')
modules_formatted = _dump_json(modules).replace('null', 'None')
fp.write(
'MODULE_ATTRIBUTE_MAP: Dict[str, List[Dict[str, Union[str, Sequence[str]]]]] = {}'.format( # noqa: E501
modules_formatted
)
f'MODULE_ATTRIBUTE_MAP: Dict[str, List[Dict[str, Union[str, Sequence[str]]]]] = {modules_formatted}' # noqa: E501
)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

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

Expand Down
13 changes: 5 additions & 8 deletions src/highdicom/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,7 @@ def __init__(
self.file_meta.ImplementationClassUID = UID(
'1.2.826.0.1.3680043.9.7433.1.1'
)
self.file_meta.ImplementationVersionName = 'highdicom{}'.format(
__version__
)
self.file_meta.ImplementationVersionName = f'highdicom{__version__}'
self.fix_meta_info(enforce_standard=True)
with BytesIO() as fp:
write_file_meta_info(fp, self.file_meta, enforce_standard=True)
Expand Down Expand Up @@ -269,9 +267,9 @@ def _copy_attribute(
raise ValueError('No tag not found for keyword "{keyword}".')
try:
data_element = dataset[tag]
logger.debug('copied attribute "{}"'.format(keyword))
logger.debug(f'copied attribute "{keyword}"')
except KeyError:
logger.debug('skipped attribute "{}"'.format(keyword))
logger.debug(f'skipped attribute "{keyword}"')
return
self.add(data_element)

Expand All @@ -297,9 +295,8 @@ def _copy_root_attributes_of_module(
from highdicom._iods import IOD_MODULE_MAP, SOP_CLASS_UID_IOD_KEY_MAP
from highdicom._modules import MODULE_ATTRIBUTE_MAP
logger.info(
'copy {}-related attributes from dataset "{}"'.format(
ie, dataset.SOPInstanceUID
)
f'copy {ie}-related attributes from '
f'dataset "{dataset.SOPInstanceUID}"'
)
iod_key = SOP_CLASS_UID_IOD_KEY_MAP[dataset.SOPClassUID]
for module_item in IOD_MODULE_MAP[iod_key]:
Expand Down
4 changes: 2 additions & 2 deletions src/highdicom/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
raise TypeError(
'Can only compare image position between instances of '
'class "{}".'.format(self.__class__.__name__)
f'class "{self.__class__.__name__}".'
)
if hasattr(self[0], 'ImagePositionPatient'):
return np.array_equal(
Expand Down Expand Up @@ -648,7 +648,7 @@ def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
raise TypeError(
'Can only compare orientation between instances of '
'class "{}".'.format(self.__class__.__name__)
f'class "{self.__class__.__name__}".'
)
if hasattr(self[0], 'ImageOrientationPatient'):
if not hasattr(other[0], 'ImageOrientationPatient'):
Expand Down
5 changes: 2 additions & 3 deletions src/highdicom/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,8 @@ def __exit__(self, except_type, except_value, except_trace) -> None:
pass
if except_value:
sys.stderr.write(
'Error while accessing file "{}":\n{}'.format(
self._filename, str(except_value)
)
f'Error while accessing file "{self._filename}":\n'
f'{except_value}'
)
for tb in traceback.format_tb(except_trace):
sys.stderr.write(tb)
Expand Down
2 changes: 1 addition & 1 deletion src/highdicom/pm/sop.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ def __init__(
frame_content_item.DimensionIndexValues = [
int(
np.where(
(dimension_position_values[idx] == pos)
dimension_position_values[idx] == pos
)[0][0] + 1
)
for idx, pos in enumerate(plane_position_values[i])
Expand Down
4 changes: 2 additions & 2 deletions src/highdicom/seg/sop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1637,7 +1637,7 @@ def __init__(
self.MaximumFractionalValue = max_fractional_value
else:
raise ValueError(
'Unknown segmentation type "{}"'.format(segmentation_type)
f'Unknown segmentation type "{segmentation_type}"'
)

self.BitsStored = self.BitsAllocated
Expand Down Expand Up @@ -2831,7 +2831,7 @@ def _get_dimension_index_values(
index_values = [
int(
np.where(
(unique_dimension_values[idx] == pos)
unique_dimension_values[idx] == pos
)[0][0] + 1
)
for idx, pos in enumerate(plane_position_value)
Expand Down
2 changes: 1 addition & 1 deletion src/highdicom/sr/coding.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __init__(
version of coding scheme
"""
super(CodedConcept, self).__init__()
super().__init__()
if len(value) > 16:
if value.startswith('urn') or '://' in value:
self.URNCodeValue = str(value)
Expand Down
35 changes: 10 additions & 25 deletions src/highdicom/sr/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1573,20 +1573,16 @@ def __init__(
PersonObserverIdentifyingAttributes):
raise TypeError(
'Observer identifying attributes must have '
'type {} for observer type "{}".'.format(
PersonObserverIdentifyingAttributes.__name__,
observer_type.meaning
)
f'type {PersonObserverIdentifyingAttributes.__name__} '
f'for observer type "{observer_type.meaning}".'
)
elif observer_type == codes.cid270.Device:
if not isinstance(observer_identifying_attributes,
DeviceObserverIdentifyingAttributes):
raise TypeError(
'Observer identifying attributes must have '
'type {} for observer type "{}".'.format(
DeviceObserverIdentifyingAttributes.__name__,
observer_type.meaning,
)
f'type {DeviceObserverIdentifyingAttributes.__name__} '
f'for observer type "{observer_type.meaning}".'
)
else:
raise ValueError(
Expand Down Expand Up @@ -2184,26 +2180,21 @@ def __init__(
if not isinstance(observer_person_context, ObserverContext):
raise TypeError(
'Argument "observer_person_context" must '
'have type {}'.format(
ObserverContext.__name__
)
f'have type {ObserverContext.__name__}'
)
self.extend(observer_person_context)
if observer_device_context is not None:
if not isinstance(observer_device_context, ObserverContext):
raise TypeError(
'Argument "observer_device_context" must '
'have type {}'.format(
ObserverContext.__name__
)
f'have type {ObserverContext.__name__}'
)
self.extend(observer_device_context)
if subject_context is not None:
if not isinstance(subject_context, SubjectContext):
raise TypeError(
'Argument "subject_context" must have type {}'.format(
SubjectContext.__name__
)
f'Argument "subject_context" must have '
f'type {SubjectContext.__name__}'
)
self.extend(subject_context)

Expand Down Expand Up @@ -3495,10 +3486,7 @@ def from_sequence(
Content Sequence containing root CONTAINER SR Content Item
"""
instance = super(
PlanarROIMeasurementsAndQualitativeEvaluations,
cls
).from_sequence(sequence)
instance = super().from_sequence(sequence)
instance.__class__ = PlanarROIMeasurementsAndQualitativeEvaluations
return cast(PlanarROIMeasurementsAndQualitativeEvaluations, instance)

Expand Down Expand Up @@ -3773,10 +3761,7 @@ def from_sequence(
Content Sequence containing root CONTAINER SR Content Item
"""
instance = super(
VolumetricROIMeasurementsAndQualitativeEvaluations,
cls
).from_sequence(sequence)
instance = super().from_sequence(sequence)
instance.__class__ = VolumetricROIMeasurementsAndQualitativeEvaluations
return cast(
VolumetricROIMeasurementsAndQualitativeEvaluations,
Expand Down
Loading

0 comments on commit 6652a16

Please sign in to comment.