diff --git a/pyiron_snippets/files.py b/pyiron_snippets/files.py index e992211..1e324a7 100644 --- a/pyiron_snippets/files.py +++ b/pyiron_snippets/files.py @@ -54,7 +54,7 @@ def __init__( self, directory: str | Path | DirectoryObject = ".", generate_unique_directory: bool | None = None, - protected: bool = False, + protected: bool | None = None, ): """ Initialize a DirectoryObject. @@ -65,8 +65,9 @@ def __init__( generate_unique_directory (bool | None): If True, generates a unique directory name, otherwise it still generates a unique name if the directory is "." and this parameter is None. - protected (bool): If True, prevents deletion of the directory object - on garbage collection. + protected (bool | None): If True, prevents deletion of the + directory object on garbage collection. If None, it defaults to + True if the directory already exists. """ if isinstance(directory, str): path = Path(directory) @@ -78,9 +79,11 @@ def __init__( directory == "." and generate_unique_directory is None ) or generate_unique_directory: path = path / f"data_{uuid.uuid4().hex}" + if protected is None: + protected = path.exists() + self._protected = protected self.path: Path = path self.create() - self._protected = protected def __getstate__(self): self._protected = True diff --git a/tests/unit/test_files.py b/tests/unit/test_files.py index f810578..8e2ac04 100644 --- a/tests/unit/test_files.py +++ b/tests/unit/test_files.py @@ -22,6 +22,16 @@ def test_directory_instantiation(self): self.assertTrue(str(directory.path).startswith("data")) self.assertEqual(len(str(directory.path)), 37) + def test_protected(self): + directory = DirectoryObject("protected", protected=True) + self.assertTrue(directory._protected) + directory = DirectoryObject("protected") + self.assertTrue(directory._protected) + directory.delete() + directory = DirectoryObject("protected") + self.assertFalse(directory._protected) + directory.delete() + def test_directory_exists(self): self.assertTrue(Path("test").exists() and Path("test").is_dir())