From 9d84aafb2467b059a5c7c68057fbbb40701f5ce2 Mon Sep 17 00:00:00 2001 From: Adrien Di Mascio Date: Thu, 11 Dec 2008 16:01:00 +0100 Subject: implement contexts.py so that it's syntax-compatible with python version < 2.5 NOTE: the previous implementation wasn't syntactically correct with python2.4 (and prior) because yield can't be used in a try/finally block until python2.5 --- contexts.py | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/contexts.py b/contexts.py index 968c9be..a1ade00 100644 --- a/contexts.py +++ b/contexts.py @@ -1,20 +1,27 @@ -try: - from contextlib import contextmanager -except ImportError: - # py < 2.5 - pass -else: - - import tempfile - import shutil +"""A few useful context managers + +:copyright: 2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. +:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr +:license: General Public License version 2 - http://www.gnu.org/licenses +""" +__docformat__ = "restructuredtext en" + +import sys - def tempdir(): - try: - path = tempfile.mkdtemp() - yield path - finally: - shutil.rmtree(path) +if sys.version_info < (2, 5): + raise ImportError("python >= 2.5 is required to import logilab.common.contexts") - # keep py < 2.4 syntax compat to avoid distribution pb - tempdir = contextmanager(tempdir) +import tempfile +import shutil +class tempdir(object): + + def __enter__(self): + self.path = tempfile.mkdtemp() + return self.path + + def __exit__(self, exctype, value, traceback): + # rmtree in all cases + shutil.rmtree(self.path) + return traceback is None + -- cgit v1.2.1