If you write software in Python you come to a point where you are testing a piece of code that expects a more or less elaborate dictionary as an argument to a function. As a good software developer we want that code properly tested but we want to use minimal fixtures to accomplish that.

So, I was looking for something that behaves like a dictionary, that you can give explicit return values for specific keys and that will give you some sort of a “default” return value when you try to access an “unknown” item (I don’t care what as long as there is no Exception raised (e.g. KeyError )).

My first thought was “why not use MagicMock?” … it’s a useful tool in so many situations.

But using MagicMock where dict is expected yields unexpected results.

First of all attribute and item access are treated differently. You setup MagicMock using key word arguments (i.e. “dict syntax”), but have to use attributes (i.e. “object syntax”) to access them.

Then I thought to yourself “why not mess with the magic methods?” __getitem__  and  __getattr__  expect the same arguments anyway. So this should work:

Well? …

… No!

By this time I thought “I can’t be the first to need this” and started searching in the docs and sure enough they provide an example for this case.

Does it work? …

Well, yes and no. It works as long as you only access those items that you have defined to be in the dictionary. If you try to access any “unknown” item you get a KeyError .

After trying out different things the simplest answer to accomplish what I set out to do seems to be sub-classing defaultdict.

And? …

Indeed, it is. 😀

Well, not quite. There are still a few comfort features missing (e.g. a proper __repr__ ). The whole, improved and tested code can be found in this Gist:

Leave a Reply

Your email address will not be published. Required fields are marked *