Lucca Marques
Lucca Marques

Reputation: 121

Change builtin function - Print

I'm trying to change the print builtin function from python. The reason I'm trying to achieve this is cause my application has an verbose sys.argv, and I want to use print to console out the message whether the verbose is True or False.

I've tried to use create a new function, but I get a recursion error:

>>> import builtins
>>> def new_print(*args, **kwargs):
...     print('print:', *args, **kwargs)
... 
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in new_print
  File "<stdin>", line 2, in new_print
  File "<stdin>", line 2, in new_print
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

I've tried using sys.stdout():

>>> import builtins
>>> import sys
>>> def new_print(*args, **kwargs):
...     sys.stdout(*args, **kwargs)
... 
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1
... )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in new_print
TypeError: '_io.TextIOWrapper' object is not callable

Although using those options, none seemed to work properly.

I need the new print function to be accesible for all my module files, without needing to import it every time. That's why I'm trying to change the builtin function, but I'm not sure that changing this in my init.py file will make a difference for my other files.

Please, if you have any idea on what could help me, please leave it below.

Upvotes: 0

Views: 650

Answers (1)

Wups
Wups

Reputation: 2569

You almost had it. Call old_print in your new function:

def new_print(*args, **kwargs):
    old_print('print:', *args, **kwargs)

old_print = print
print = new_print

Upvotes: 1

Related Questions