A very simple proof-of-concept of an ostreams-like interface wrapping around file-like objects, included a demonstration of manipulators.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import sys
class IOManipulator:
def __init__(self, function=None):
self.function = function
def do(self, output):
self.function(output)
class OStream:
def __init__(self, output=None):
if output is None:
output = sys.stdout
self.output = output
def __lshift__(self, thing):
if isinstance(thing, IOManipulator):
thing.do(self.output)
else:
self.output.write(str(thing))
return self
def main():
endl = IOManipulator(lambda s: (s.write('\n'), s.flush()))
cout = OStream()
cout << "The average of " << 1 << " and " << 3 << " is " << (1 + 3)/2 << endl
if __name__ == '__main__': main()
|
Although the Python streams model does not make it necessary, it is quite easy to make a wrapper around file-like objects that behaves like the C++ ostreams' insertion operator (e.g., cout Although the Python streams model does not make it necessary, it is quite easy to make a wrapper around file-like objects that behaves like the C++ ostreams' insertion operator (e.g., cout
really nice ! :o) (nt).
Much simpler to use than "The average of %d and %d is %f\n" % ...! But define endl in the module with IOManip and OStream - don't want to have to reinvent it every time.
Nice, but. Better use
instead of
str(thing) can fail, if the thing is an unicode string.
very nice and surprisingly simple!