You could reuse the 'with' idiom to do this reliably: create tmpdir on __enter__ and rmtree on __exit__.