From 940f60fe5b0f7b14a6b29ca6d48179265aa85306 Mon Sep 17 00:00:00 2001 From: Vitja Makarov Date: Tue, 30 Jul 2013 21:17:57 +0400 Subject: [PATCH] contextmanagers: Put state restore code into finally block --- blessings/__init__.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/blessings/__init__.py b/blessings/__init__.py index 68212c25..276565b6 100644 --- a/blessings/__init__.py +++ b/blessings/__init__.py @@ -235,24 +235,29 @@ def location(self, x=None, y=None): self.stream.write(self.move_x(x)) elif y is not None: self.stream.write(self.move_y(y)) - yield - - # Restore original cursor position: - self.stream.write(self.restore) + try: + yield + finally: + # Restore original cursor position: + self.stream.write(self.restore) @contextmanager def fullscreen(self): """Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.""" self.stream.write(self.enter_fullscreen) - yield - self.stream.write(self.exit_fullscreen) + try: + yield + finally: + self.stream.write(self.exit_fullscreen) @contextmanager def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) - yield - self.stream.write(self.normal_cursor) + try: + yield + finally: + self.stream.write(self.normal_cursor) @property def color(self):