I found these two alternatives to create a modified version of the print()
function. However, that means that the new print function is usable only within the module being executed.
- Using decorators
def my_decorator(func):
def wrapped_func(*args, **kwargs):
return func("123abc -", *args, **kwargs)
return wrapped_func
my_print = my_decorator(print)
my_print("My message")
Output: 123abc - My message
- Using the bultins
import builtins
def my_print(*args):
builtins.print("123abc -", *args)
my_print("My message")
Output: 123abc - My message
Update:
To modify the print()
function saved in the builtins package to have its effects anytime and anywhere print is used (so that the modification only needs to be performed once in the whole script) you can use the code below. I found it in this thread: https://stackoverflow.com/a/13871861/21905824
def modify_print_builtin():
try:
import __builtin__ as builtins # Python 2
except ImportError:
import builtins # Python 3
_print = print # keep a local copy of the original print
builtins.print = lambda *args, **kwargs: _print("123abc -", *args, **kwargs)
modify_print_builtin()
print("My message")