0

I wrote the following code to manage a temporary directory.

class TempDirectory(object):
    def __init__(self):
        self.path = None
    def __enter__(self):
        self.path = tempfile.mkdtemp()
        print self.path
    def __exit__(self, exc_type, exc_value, traceback):
        def warn(function, path, excinfo):
            print "warning: could not remove temporary object '%s'"%path
        shutil.rmtree(self.path, True, warn)

However when I try to use it:

with TempDirectory() as tempdir:
    print tempdir

tempdir is always None. This is a problem, because then I can't access the path of the temporary directory!

I've poured over the reference documentation for the with statement in 2.7, and I can't see any significant difference between my code and the example presented here.

What's happening to my TempDirectory instance?

Mike
  • 105
  • 2
  • 5
  • To be honest I can probably make do without a context-manager for this, but I really want to know why it doesn't work. – Mike Jun 13 '15 at 02:19
  • Try returning something in `__enter__`. Perhaps returning `self.path` or something along that line. – Shashank Jun 13 '15 at 02:20

0 Answers0