overload print python

user34537 picture user34537 · Feb 15, 2009 · Viewed 81.4k times · Source

Am I able to overload the print function and call the normal function from within? What I want to do is after a specific line I want print to call my print which will call the normal print and write a copy to file.

Also I don't know how to overload print. I don't know how to do variable length arguments. I'll look it up soon but overload print python just told me I can't overload print in 2.x which is what I am using.

Answer

DevPlayer picture DevPlayer · Apr 11, 2012

For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.

In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:

from __future__ import print_function
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments, other future statements, or blank lines before the __future__ line.

try:
    import __builtin__
except ImportError:
    # Python 3
    import builtins as __builtin__

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    __builtin__.print('My overridden print() function!')
    return __builtin__.print(*args, **kwargs)

Of course you'll need to consider that this print function is only module wide at this point. You could choose to override __builtin__.print, but you'll need to save the original __builtin__.print; likely mucking with the __builtin__ namespace.