Created
August 26, 2013 17:35
-
-
Save dansondergaard/6344209 to your computer and use it in GitHub Desktop.
I recently discovered this awesome redirection syntax for the print statement in Python. Also, it reveals quite nicely that print writes the newline separately to the stream.
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 Logger(object): | |
| def __init__(self): | |
| self.records = [] | |
| def write(self, record): | |
| self.records.append(record) | |
| logger = Logger() | |
| print >> logger, "hello" | |
| print >> logger, "world" | |
| print logger.records | |
| # > ['hello', '\n', 'world', '\n'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fun fact: If the first expression (in this case 'logger') evaluates to None then the result is printed to stdout.