From 944216964ab553d7cde691cb4c47739cdf4156f7 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Tue, 3 May 2005 16:57:17 +0000 Subject: [PATCH] Add another example (saving sys.stout). Eradicate tabs. --- pep-0340.txt | 56 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/pep-0340.txt b/pep-0340.txt index be4ec4f77..68874c7e8 100644 --- a/pep-0340.txt +++ b/pep-0340.txt @@ -558,26 +558,42 @@ Examples 6. It is possible to write a regular iterator with the semantics of example 1: - class locking: - def __init__(self, lock): - self.lock = lock - self.state = 0 - def __next__(self, arg=None): - # ignores arg - if self.state: - assert self.state == 1 - self.lock.release() - self.state += 1 - raise StopIteration - else: - self.lock.acquire() - self.state += 1 - return None - def __exit__(self, type, value=None, traceback=None): - assert self.state in (0, 1, 2) - if self.state == 1: - self.lock.release() - raise type, value, traceback + class locking: + def __init__(self, lock): + self.lock = lock + self.state = 0 + def __next__(self, arg=None): + # ignores arg + if self.state: + assert self.state == 1 + self.lock.release() + self.state += 1 + raise StopIteration + else: + self.lock.acquire() + self.state += 1 + return None + def __exit__(self, type, value=None, traceback=None): + assert self.state in (0, 1, 2) + if self.state == 1: + self.lock.release() + raise type, value, traceback + + 7. Redirect stdout temporarily: + + def saving_stdout(new_stdout): + save_stdout = sys.stdout + try: + sys.stdout = new_stdout + yield + finally: + sys.stdout = save_stdout + + Used as follows: + + block opening(filename, "w") as f: + block saving_stdout(f): + print "Hello world" Acknowledgements