diff --git a/mutapath/decorator.py b/mutapath/decorator.py index b07c82b..f418734 100644 --- a/mutapath/decorator.py +++ b/mutapath/decorator.py @@ -8,7 +8,7 @@ __EXCLUDE_FROM_WRAPPING = ["__dir__", "__eq__", "__format__", "__repr__", "__str__", "__sizeof__", "__init__", "__post_init__", "__getattribute__", "__delattr__", "__setattr__", "__getattr__", "__exit__", "__fspath__", "'_Path__wrap_attribute'", "__wrap_decorator", "_op_context", - "__hash__", "_norm"] + "__hash__", "__enter__", "_norm", "open"] __MUTABLE_FUNCTIONS = {"rename", "renames", "copy", "copy2", "copyfile", "copymode", "copystat", "copytree", "move", "basename", "abspath", "join", "joinpath", "normpath", "relpath", "realpath", "relpathto"} diff --git a/mutapath/immutapath.py b/mutapath/immutapath.py index 004e5da..131edb0 100644 --- a/mutapath/immutapath.py +++ b/mutapath/immutapath.py @@ -1,5 +1,6 @@ from __future__ import annotations +import io import os import pathlib from contextlib import contextmanager @@ -111,10 +112,10 @@ def __rdiv__(self, other): __rtruediv__ = __rdiv__ def __enter__(self): - return self._contained.__enter__() + return Path(self._contained.__enter__()) def __exit__(self, *_): - return self._contained.__exit__() + self._contained.__exit__() def __fspath__(self): return self._contained.__fspath__() @@ -357,6 +358,14 @@ def owner(self): """ return self._contained.owner + def open(self, *args, **kwargs): + """ + Open a file and return a stream to its content. + + seealso:: :func:`io.open` + """ + return io.open(str(self), *args, **kwargs) + @contextmanager def mutate(self): """ diff --git a/tests/test_with_path.py b/tests/test_with_path.py index baa37af..f079efb 100644 --- a/tests/test_with_path.py +++ b/tests/test_with_path.py @@ -37,6 +37,18 @@ def test_wrapped_generator(self): finally: self._clean() + def test_open(self): + try: + test_file = self._gen_start_path() + expected = "test" + with test_file.open("w") as w: + w.write(expected) + actual = test_file.text() + self.assertEqual(expected, actual) + self.assertIsInstance(test_file, Path) + finally: + self._clean() + def test_size(self): try: test_file = self._gen_start_path()