Decorating Python's builtin print() function

后端 未结 4 656
夕颜
夕颜 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:03

    Aside from BrenBarn's answer(accepted), posting another gist here by @Adam Smith

    import builtins
    import functools
    import json
    
    orig_print = builtins.print
    
    def indent4(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            return f(json.dumps(*args, **kwargs, indent=4))
        return wrapped
    
    @indent4
    def print(*args, **kwargs):
        return orig_print(*args, **kwargs)
    

提交回复
热议问题