medium +20 pts

Temporary directory manager

Build a reusable context manager that creates a temporary directory and cleans it up on exit.

Implement a context manager class `TempDir` that can be used with `with TempDir() as t:`. When entering the context, the class should create a new unique temporary directory inside the system's default temporary directory (use `tempfile.mkdtemp()`). The object returned by `__enter__` must be the `TempDir` instance itself (so that `as t` gives you the object with an accessible `path` attribute). When exiting the context normally, the temporary directory and all its contents must be removed. If an exception occurs inside the `with` block, the directory must still be removed, and the exception must propagate unchanged. The class should expose a public attribute `path` (a string) that contains the full path to the created temporary directory. This path is available only while inside the context; after exiting, `path` still exists but the directory is deleted. The context manager should be re-usable: each use of `with TempDir() as t:` must create a fresh temporary directory. Implement the class with methods `__enter__` and `__exit__`. Do not use `contextlib.contextmanager`; implement the class manually. Your `__enter__` must return `self`.

Constraints

The implementation must work on any platform (POSIX/Windows). Assume the underlying filesystem allows creating and deleting temporary files. The number of entries inside the temporary directory is small (less than 1000). Your code must handle arbitrary exceptions inside the with block.

Example

>>> import os
>>> with TempDir() as t:
...     print(os.path.isdir(t.path))
...     with open(os.path.join(t.path, 'file.txt'), 'w') as f:
...         f.write('hello')
...     print(os.path.exists(os.path.join(t.path, 'file.txt')))
True
True
>>> print(os.path.exists(t.path))  # cleaned up after exit
False
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

In `__enter__`, set `self.path = tempfile.mkdtemp()` and then `return self`.
In `__exit__`, always call `shutil.rmtree(self.path, ignore_errors=True)` to ensure cleanup even if an exception is pending.
Remember that `__exit__` should return `False` (or `None`) so that exceptions are not suppressed.
For reusability, each call to `__enter__` should create a new directory, possibly overwriting the previous `path`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.