Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorating Python's builtin print() function

As we know in Python 3 print() is a function, is it possible to create a decorated version of it wrapped under json.dumps(indent=4)

for ex.

Calling print(mydict) should produce the same result as print(json.dumps(mydict, indent=4))

like image 859
nehem Avatar asked Oct 10 '17 04:10

nehem


People also ask

How do you decorate a print in Python?

Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. # inside the wrapper function. def function_to_be_used():

How do you decorate a function in Python?

To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function. Here, when we decorate, multiply_together with integer_check, the integer function gets called.

What does the print function do in Python?

The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

What are the inbuilt decorators in Python?

Some commonly used decorators that are even built-ins in Python are @classmethod , @staticmethod , and @property . The @classmethod and @staticmethod decorators are used to define methods inside a class namespace that are not connected to a particular instance of that class.


1 Answers

You don't need a decorator per se to do that. Just define a new function and call it print:

import builtins

def print(*args, **kwargs):
    builtins.print(json.dumps(*args, **kwargs, indent=4))

You can use the builtins module as shown to access the original print function.

The thing is that doing this doesn't really gain anything over calling your new function something besides print, except it will confuse people.

If you want to really confuse people you could store old_print = builtins.print, define your new function as my_print (accessing the original as old_print) and then do builtins.print = my_print. Then your modified print will actually replace the regular print, even in other modules that know nothing about your shenanigans. But that is an even worse idea.

like image 92
BrenBarn Avatar answered Oct 21 '22 02:10

BrenBarn