Last active
June 12, 2020 21:45
-
-
Save cizixs/6211652 to your computer and use it in GitHub Desktop.
Using c++ stream operator << in python. This gist is from python cookbook.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class IOManipulator(object): | |
| def __init__(self, function=None): | |
| self.function = function | |
| def do(self, output): | |
| self.function(output) | |
| def do_endl(stream): | |
| stream.output.write('\n') | |
| stream.output.flush() | |
| endl = IOManipulator(do_endl) | |
| class OStream(object): | |
| def __init__(self, output=None): | |
| if output is None: | |
| import sys | |
| output = sys.stdout | |
| self.output = output | |
| self.format = '%s' | |
| def __lshift__(self, thing): | |
| '''Python will call this function when you use << with left operator being OStream | |
| ''' | |
| if isinstance(thing, IOManipulator): | |
| thing.do(self) | |
| else: | |
| self.output.write(self.format % thing) | |
| self.format = '%s' | |
| return self | |
| def example_main(): | |
| cout = OStream() | |
| cout << "The average of " << 1 << " and " << 3 << " is " << (1+3)/2 << endl | |
| if __name__ == '__main__': | |
| example_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment