Python and dictionary like object

thomas picture thomas · Aug 14, 2009 · Viewed 10.7k times · Source

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).

But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered bad, as I can read on almost every Pythonista's blog).

But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?

Thanks!

Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : http://blog.cafeaumiel.com/public/python/dict_deep_update.py

Answer

Anon picture Anon · Aug 14, 2009

Check out the (new in 3.x) abstract base classes (ABC's) in the collections module:

http://docs.python.org/3.1/library/collections.html

I would consider checking with isinstance against Mapping like in the following:

>>> import collections
>>> isinstance({},collections.Mapping)
True

Then, if you make your own dict-like class, make collections.Mapping one of its bases.

The other route is trying and catching whatever exceptions for the dictionary operations, - but with the recursion you're talking about, I'd rather check against the base type first than handle figuring out what dict or subdict or other dict member was or was not there to throw an exception.

Editing to add: The benefit of checking against the Mapping ABC instead of against dict is that the same test will work for dict-like classes regardless of whether or not they subclass dict, so it's more flexible, just in case.