1515from . import config , formats , hooks
1616from .converters import Converter , List , map_type , resolve
1717from .types import Missing , Trilean
18- from .utils import display , get_default_field_value , recursive_update , write
18+ from .utils import display , get_default_field_value , recursive_update , remove , write
1919
2020
2121class Mapper :
@@ -264,6 +264,17 @@ def save(self, *, include_default_values: Trilean = None, _log=True) -> None:
264264 self ._root .save (include_default_values = include_default_values , _log = _log )
265265 return
266266
267+ # Determine whether the attributes that are involved in the path were changed
268+ file_rename_required = False
269+ original_path = self .path
270+ with hooks .disabled (): # hooks have to be disabled to prevent infinite loop
271+ if "path" in self .__dict__ :
272+ del self .__dict__ ["path" ] # invalidate the cached property
273+
274+ # This call of self.path updates the value since the cache is invalidated
275+ if self .path != original_path :
276+ file_rename_required = True
277+
267278 if self .path :
268279 if self .exists and self ._frozen :
269280 raise dataclasses .FrozenInstanceError (
@@ -279,6 +290,8 @@ def save(self, *, include_default_values: Trilean = None, _log=True) -> None:
279290 text = self ._get_text (include_default_values = include_default_values )
280291
281292 write (self .path , text , display = True )
293+ if file_rename_required :
294+ remove (original_path )
282295
283296 self .modified = False
284297
0 commit comments