Is it possible to “hack” Python's print function?

前端 未结 4 740
灰色年华
灰色年华 2020-11-30 18:02

Note: This question is for informational purposes only. I am interested to see how deep into Python\'s internals it is possible to go with this.

Not very long ago, a

4条回答
  •  醉话见心
    2020-11-30 18:10

    Let's combine this with frame introspection!

    import sys
    
    _print = print
    
    def print(*args, **kw):
        frame = sys._getframe(1)
        _print(frame.f_code.co_name)
        _print(*args, **kw)
    
    def greetly(name, greeting = "Hi")
        print(f"{greeting}, {name}!")
    
    class Greeter:
        def __init__(self, greeting = "Hi"):
            self.greeting = greeting
        def greet(self, name):
            print(f"{self.greeting}, {name}!")
    

    You'll find this trick prefaces every greeting with the calling function or method. This might be very useful for logging or debugging; especially as it lets you "hijack" print statements in third party code.

提交回复
热议问题