How can I use monkey patching in Python to replace a specific argument?
Question: I want to use monkey patching to change all statements such as `time.sleep(5)`
to `myServer.sleep(5)`. How can I realize it? Thank you very much!

    
    
    import test
    import subprocess
    import ast
    import os
    import time
    import sys
    
    if __name__ == "__main__":
    
        def insomniac(duration):
            pass  # don't sleep
    
        _original_sleep = time.sleep
        time.sleep = insomniac
    
        def dont_write(stuff):
            pass  # don't write
    
        _original_write = sys.stdout.write
        sys.stdout.write = dont_write
    
        execfile("test.py")
    
        exit(0)
    


Answer: If your focus is on testing, i.e. you want to ensure that a callable in some
external library out of your control is called in a specific way, there are
testing libraries that can help you with this, such as
[`mock`](https://pypi.python.org/pypi/mock). It can be pretty involving to set
all those things up correctly so when I do coding I typically try to structure
my code in a way that minimizes the usage of mocks.

Take a look at the [documentation for
`mock`](http://www.voidspace.org.uk/python/mock/) if you really want to get
your toes wet towards this direction. While at this, you probably should
formalize your testing techniques to make use of
[`unitttest`](http://docs.python.org/library/unittest.html). If you are lost,
[Writing unit tests in Python: How do I
start?](http://stackoverflow.com/questions/3371255/writing-unit-tests-in-
python-how-do-i-start).

