pythonpython-3.xmethodspython-object

Is there a way to override the print method in Python 3.x?


Pretty simple question - I have searched but not found an answer to this question.

It might be a bit silly to do this but I was curious if it is possible to hook into the print(*arg, **kwarg) function of python 3.X and override it / add time.sleep(var) at the end of the invoke.

Of course I could just def another method and wrap it with a time.sleep(var) but I was just curious how one would go about overriding the pre-built functions.


Solution

  • If you want to patch any function globally, e.g. for testing / debugging purposes, the safest way is to use unittest.mock.patch():

    def x():
        '''the code under test'''
        print('Hello, world!')
    
    ...
    from unittest.mock import patch
    orig_print = print
    
    with patch('builtins.print') as m:
        def my_print(*args, **kwargs):
            orig_print('PATCHED:', *args, **kwargs)
    
        m.side_effect = my_print
    
        x()  # prints 'PATCHED: Hello, world!'
    
    # prints 'Hello, world!', because the patch context is exited
    # and the original function is restored: 
    x()