Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Created August 26, 2013 17:35
Show Gist options
  • Select an option

  • Save dansondergaard/6344209 to your computer and use it in GitHub Desktop.

Select an option

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.
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']
@reynir
Copy link

reynir commented Aug 26, 2013

Fun fact: If the first expression (in this case 'logger') evaluates to None then the result is printed to stdout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment