Welcome, guest | Sign In | My Account | Store | Cart

A very simple proof-of-concept of an ostreams-like interface wrapping around file-like objects, included a demonstration of manipulators.

Python, 32 lines
 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

4 comments

kolja 20 years, 10 months ago  # | flag

really nice ! :o) (nt).

Paul McGuire 20 years, 6 months ago  # | flag

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.

Gregor Rayman 20 years, 6 months ago  # | flag

Nice, but. Better use

self.output.write("%s" % thing)

instead of

self.output.write(str(thing))

str(thing) can fail, if the thing is an unicode string.

Peter Schwalm 20 years, 5 months ago  # | flag

very nice and surprisingly simple!