From 9c52a332d8caafdeba2884c6c708a6ce8f3aef34 Mon Sep 17 00:00:00 2001 From: neingeist Date: Thu, 24 Apr 2014 14:18:24 +0200 Subject: [PATCH] add some simple context manager aka "with" test --- context-managers.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 context-managers.py diff --git a/context-managers.py b/context-managers.py new file mode 100755 index 0000000..083ffa6 --- /dev/null +++ b/context-managers.py @@ -0,0 +1,29 @@ +from contextlib import contextmanager +import os + + +@contextmanager +def working_directory(path): + current_dir = os.getcwd() + os.chdir(path) + try: + yield + finally: + os.chdir(current_dir) + + +@contextmanager +def just_a_test(): + try: + print "just trying..." + yield + finally: + print "finally!" + + +with working_directory("/tmp"), just_a_test(): + # do something within data/stuff + print os.getcwd() + +# here I am back again in the original working directory +print os.getcwd()