Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ Easily indicate that some functionality is being deprecated
Raises a warning like `DeprecationWarning: __main__.foo is deprecated: Use bar(a, b) instead. It is not guaranteed to be in service in vers. 0.5.0 foo(1, 2)`


## Directory context

A context manager that changes the current working directory to the given path upon entering the context and reverts to the original directory upon exiting.
If the specified path does not exist, it is created.

```python
>>> import os
>>> from pyiron_snippets.directory_context import set_directory
>>> directory_before_context_is_applied = os.getcwd()
>>> with set_directory("tmp"):
... os.path.relpath(os.getcwd(), directory_before_context_is_applied)
'tmp'

```


## DotDict

A dictionary that allows dot-access. Has `.items()` etc.
Expand Down
35 changes: 35 additions & 0 deletions pyiron_snippets/directory_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import os
from contextlib import contextmanager
from pathlib import Path


@contextmanager
def set_directory(path: Path | str):
"""
A context manager that changes the current working directory to the given path
upon entering the context and reverts to the original directory upon exiting.
If the specified path does not exist, it is created.

Parameters:
path: Path | str
The target directory path to set as the current working directory.
If it does not exist, it will be created.

Examples:
Change the directory to the path "tmp" within the context:

>>> import os
>>> from pyiron_snippets.directory_context import set_directory
>>> directory_before_context_is_applied = os.getcwd()
>>> with set_directory("tmp"):
... os.path.relpath(os.getcwd(), directory_before_context_is_applied)
'tmp'

"""
origin = Path().absolute()
try:
os.makedirs(path, exist_ok=True)
os.chdir(path)
yield
finally:
os.chdir(origin)
19 changes: 19 additions & 0 deletions tests/unit/test_directory_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os
import unittest

from pyiron_snippets.directory_context import set_directory


class TestContextDirectory(unittest.TestCase):
def test_set_directory(self):
current_directory = os.getcwd()
test_directory = "context"
with set_directory(path=test_directory):
context_directory = os.getcwd()
self.assertEqual(
os.path.relpath(context_directory, current_directory), test_directory
)


if __name__ == "__main__":
unittest.main()
Loading