Overwrite built-in function

user3099519 picture user3099519 · Dec 13, 2013 · Viewed 12.1k times · Source

I have a large chunk of code which uses the "print" statement. As to say in this way:

print "foo"

and not

print("foo")

I want to alter the output. Can I do this without changing all the lines with print? For example by overwriting the function/statement?

Answer

Martijn Pieters picture Martijn Pieters · Dec 13, 2013

Python directly supports what you want to do:

from __future__ import print_function

Any module with that line at the top will treat the print statement as a function instead, making the code compatible with both Python 2 and 3.

This applies just to the print statement; you cannot override other statements.

This does mean you then have to use print() as a function everywhere in that module, but you can then also provide your own implementation if you so desire:

from __future__ import print_function
import __builtin__

def print(*args, **kwargs):
    __builtin__.print('Prefixed:', *args, **kwargs)

print('Hello world!')

Another option is to use a context manager to capture printed statements, directing the output away from sys.stdout into a in-memory file object of your choosing:

from contextlib import contextmanager
import sys
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO


@contextmanager
def capture_sys_output():
    caputure_out = StringIO()
    current_out = sys.stdout
    try:
        sys.stdout = caputure_out
        yield caputure_out
    finally:
        sys.stdout = current_out

and wrap any blocks that you want to capture print output for with the context manager. Here is an example prefixing printed lines:

with capture_sys_output as output:
    print 'Hello world!'

output = output.get_value()
for line in output.splitlines():
    print 'Prefixed:', line

or even provide a wrapper:

from contextlib import contextmanager
import sys

class Prefixer(object):
    def __init__(self, prefix, orig):
        self.prefix = prefix
        self.orig = orig
    def write(self, text):
        self.orig.write(self.prefix + text)
    def __getattr__(self, attr):
        return getattr(self.orig, attr)     

@contextmanager
def prefix_stdout(prefix):
    current_out = sys.stdout
    try:
        sys.stdout = Prefixer(prefix, current_out)
        yield
    finally:
        sys.stdout = current_out

and use as:

with prefix_stdout('Prefixed: '):
    print 'Hello world!'

but take into account that print statements usually write data to stdout in separate chunks; the newline at the end is a separate write.