parent
45c25ac443
commit
944216964a
56
pep-0340.txt
56
pep-0340.txt
|
@ -558,26 +558,42 @@ Examples
|
||||||
6. It is possible to write a regular iterator with the
|
6. It is possible to write a regular iterator with the
|
||||||
semantics of example 1:
|
semantics of example 1:
|
||||||
|
|
||||||
class locking:
|
class locking:
|
||||||
def __init__(self, lock):
|
def __init__(self, lock):
|
||||||
self.lock = lock
|
self.lock = lock
|
||||||
self.state = 0
|
self.state = 0
|
||||||
def __next__(self, arg=None):
|
def __next__(self, arg=None):
|
||||||
# ignores arg
|
# ignores arg
|
||||||
if self.state:
|
if self.state:
|
||||||
assert self.state == 1
|
assert self.state == 1
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
self.state += 1
|
self.state += 1
|
||||||
raise StopIteration
|
raise StopIteration
|
||||||
else:
|
else:
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
self.state += 1
|
self.state += 1
|
||||||
return None
|
return None
|
||||||
def __exit__(self, type, value=None, traceback=None):
|
def __exit__(self, type, value=None, traceback=None):
|
||||||
assert self.state in (0, 1, 2)
|
assert self.state in (0, 1, 2)
|
||||||
if self.state == 1:
|
if self.state == 1:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
raise type, value, traceback
|
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
|
Acknowledgements
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue