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))
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():
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With