Paul
Paul

Reputation: 3361

What does "dict-like" mean in Python?

Occasionally people refer to "X-like" objects in Python. Example:

data_iter_maker – A zero-argument callable which returns an iterator over dict-like data objects.

Does "dict-like" have a precise definition, and if so, what is it? Would it be an object x that can be indexed like a dictionary can: x[a], where a is a hashable? In that case, a namedtuple might not be considered dict-like, since you can't index using an expression like x['a'] (last I checked you have to write x.a). But on the other hand, namedtuples are functionally so similar to dicts that I'm not sure what to think.

Cynically, I'm tempted to guess that "dict-like" means "an object similar enough to dict that my code will produce the same answer as if you had submitted a semantically equivalent dict object". In other words, "run the function and find out for yourself if your argument is dict-like!"

More generally, is an X-like object one which implements the same interface as X?

Upvotes: 15

Views: 4721

Answers (2)

Mike Müller
Mike Müller

Reputation: 85482

Practical duck typing:

dict_meths = set(dir({}))

# Python3
class A:
    pass

default_meths = set(dir(A()))

diff = dict_meths - default_meths

Now diff is:

{'__contains__',
 '__delitem__',
 '__getitem__',
 '__iter__',
 '__len__',
 '__setitem__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values'}

When you implement all these methods in your class, you certainly have a dict-like object. If some of the less common ones such as update are missing you may still talk about a dict-like object. Compare file-like objects.

Upvotes: 6

DilithiumMatrix
DilithiumMatrix

Reputation: 18637

Python uses 'duck-typing':

“If it looks like a duck and quacks like a duck, it must be a duck.”

Or perhaps, "If it looks like a duck and quacks like a duck, it is sufficiently close to a duck to treat it like one." Obviously the first sounds better. This is closely related to the python doctrine of "Easier to Ask for Forgiveness than to ask for Permission".

A dict-like object is one which implements (or emulates) the dictionary interface. The same concept often comes up for iterables, and often in numpy for 'array-like' (or 'array_like') objects.

Upvotes: 9

Related Questions