Makes for a very unpythonic feeling API. I’d be interested to hear why the author settled on this design, and see example uses that he likes the look of. Are there any other libraries which use this pattern?
You can either use mock(obj, {'x': 1, 'y': 2}) or mock(obj, 'x', 1, 'y', 2). I thought it'll be nice to provide both options, but you might be right and using just a dict of mocks is more Pythonic.
This can then also be called (using the built-in double-star-unpacking feature) as:
mock(obj, **{'x': 1, 'y': 2})
or even
mock(obj, **dict([('x', 1), ('y', 2)]))
Then there’s no explicit need to support multiple alternative function signatures, and in particular you don’t get people using the (quite atypical and therefore semantically ambiguous):
Comments
The line where the original attributes are backed up needs to be a deep copy (otherwise the updates will affect the backed up dictionary):
self.orig = self.obj.__dict__
Should be more like:
self.orig = self.obj.__dict__.copy()
Agreed. I did the following:
This doesn't perform a deep copy, but prevents modifications on self.obj.__dict__ from modifying self.original also.You can either use mock(obj, {'x': 1, 'y': 2}) or mock(obj, 'x', 1, 'y', 2). I thought it'll be nice to provide both options, but you might be right and using just a dict of mocks is more Pythonic.
At risk of bikeshedding, I think the "most pythonic" approach would be mock(obj, x=1, y=2)
Seriously though, cool lib, thanks for it =)
Yes, the most pythonic is:
Which you get by: This can then also be called (using the built-in double-star-unpacking feature) as: or even Then there’s no explicit need to support multiple alternative function signatures, and in particular you don’t get people using the (quite atypical and therefore semantically ambiguous):Thanks, updated the code to use keyword arguments only.
For another clever take on mocking in Python, check out Ian Bicking's minimock: http://blog.ianbicking.org/minimock.html
I'm getting more intimate with Python and also made a small mocking library, I'm looking for constructive feedback: https://github.com/paolovictor/mockaccino