Search code examples
pythonmonkeypatching

How can I get pointer type behaviour in python


I want to write a test case which will test a list of functions. Here is an example of what I want to do:

from mock import Mock
def method1 ():
    pass

def method2 ():
    pass

## The testcase will then contain:
for func in method_list:
    func = Mock()
    # continue to setup the mock and do some testing

What I want to achieve is as follows:
Step 1) Assign my local method variable to each item in method_list
Step 2) Monkeypatch the method. In this example I am using a mock.Mock object

What actually occurs is:
Step 1) method is successfully assigned to an item from method_list - OK
Step 2) method is then assigned to the object Mock() - NOK

What I wanted in step 2 was to get the item from method_list e.g. method1 to be assigned to the Mock() object. The end result would be that both method and method1 would point to the same Mock() object

I realise that what I am essentially doing is a = b
a = c
and then expecting c==b !

I guess this is not really possible with out somehow getting a pointer to b ?


Solution

  • If I understand you correctly, you want to change what the variable method1 points to? Is that right?

    You can do this by modifying its entry in the dictionary of local variables:

    for method_name in [ 'method1', 'method2' ]:
        locals()[ method_name ] = Mock( )
    

    The reason your previous code doesn't do what you want is that func is a reference to the function method1. By assigning to is, you simply change what it points to.

    Are you sure you want to do this?

    Monkeypatching is nasty and can cause many problems.