Decorating Python's builtin print() function

后端 未结 4 658
夕颜
夕颜 2021-01-18 05:36

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.

4条回答
  •  一向
    一向 (楼主)
    2021-01-18 06:06

    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.

提交回复
热议问题