views:

40

answers:

1

I'm a relative newcomer to python and I'm just wondering if there is some equivalent to the map coercion feature available in groovy.

For context, I am writing a unit test and want to mock a class with a simple two method interface, in groovy I would do the following:

mock = [apply:{value -> return value*2 }, isValid:{return true}]
testObject.applyMock(mock)

i.e, mock can be treated as an object with a class like:


class mock:

    def apply(self, value):
        return value *2

    def isValid(self):
        return true

Is there a nice pythonic way to achieve this?

Cheers Alex

+2  A: 

Use the 3-parameter form of type():

mock = type('mock', (object,), {'apply': (lambda self, value: value * 2),
  'isValid': lambda self: True})
Ignacio Vazquez-Abrams
That seems to do the trick, it took me a little while to realize that the result of the call is a type and not an instance. So in order to use the mock you need to do something like mockObject = mock().Thanks very much
Alex