Skip to content

Commit

Permalink
FIX: make update unalter the path instance if check fails (#950)
Browse files Browse the repository at this point in the history
* FIX: make update unalter the path instance if check fails

* fix

* update what's new

Co-authored-by: Richard Höchenberger <richard.hoechenberger@gmail.com>
  • Loading branch information
agramfort and hoechenberger committed Jan 31, 2022
1 parent 92258b2 commit 5a4c82a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 2 additions & 0 deletions doc/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ Bug fixes

- Avoid ``DeprecationWarning`` in :func:`mne_bids.inspect_dataset` with the upcoming MNE-Python 1.0 release, by `Richard Höchenberger`_ (:gh:`942`)

- Avoid modifying the instance of :class:`mne_bids.BIDSPath` if validation fails when calling :meth:`mne_bids.BIDSPath.update`, by `Alexandre Gramfort`_ (:gh:`950`)

:doc:`Find out what was new in previous releases <whats_new_previous_releases>`

.. include:: authors.rst
14 changes: 12 additions & 2 deletions mne_bids/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ def update(self, *, check=None, **kwargs):
kwargs['extension'] = f'.{extension}'

# error check entities
old_kwargs = dict()
for key, val in kwargs.items():

# check if there are any characters not allowed
Expand All @@ -728,15 +729,24 @@ def update(self, *, check=None, **kwargs):
# set entity value, ensuring `root` is a Path
if val is not None and key == 'root':
val = Path(val).expanduser()
old_kwargs[key] = \
getattr(self, f'{key}') if hasattr(self, f'_{key}') else None
setattr(self, f'_{key}', val)

# infer datatype if suffix is uniquely the datatype
if self.datatype is None and \
self.suffix in SUFFIX_TO_DATATYPE:
self._datatype = SUFFIX_TO_DATATYPE[self.suffix]

# Perform a check of the entities.
self._check()
# Perform a check of the entities and revert changes if check fails
try:
self._check()
except Exception as e:
old_check = self.check
self.check = False
self.update(**old_kwargs)
self.check = old_check
raise e
return self

def match(self, check=False):
Expand Down
9 changes: 9 additions & 0 deletions mne_bids/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -1134,3 +1134,12 @@ def test_datasetdescription_with_bidspath(return_bids_test_dir):
bids_path.update(suffix='dataset_description', check=False)
assert bids_path.fpath.as_posix() == \
Path(f'{return_bids_test_dir}/dataset_description.json').as_posix()


def test_update_fail_check_no_change():
bids_path = BIDSPath(subject='test')
try:
bids_path.update(suffix='ave')
except Exception:
pass
assert bids_path.suffix is None

0 comments on commit 5a4c82a

Please sign in to comment.