Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does isinstance with a dictionary and abc.Mapping from collections doing?

The code I'm running is:

>>> from collections import abc
>>> mydict = {'test_key': 'test_value'}
>>> isinstance(mydict, abc.Mapping)
True

I understand what isinstance does, but I'm not sure what abc.Mapping does from collections?

It seems like the line isinstance(mydict, abc.Mapping) is being used to check that mydict is a dictionary?

Wouldn't it just be easier to do isinstance(mydict, dict)?

I did some searching and found related comments in this thread: What is the best (idiomatic) way to check the type of a Python variable?, but I'm still having trouble figuring out why using abc.Mapping is preferable here than just using dict.

like image 738
Vincent Avatar asked Feb 29 '16 01:02

Vincent


1 Answers

collections.abc provide a serie of Abstract Base Classes for container

This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.

they allow you to check if a certain object have a behavior similar to that of the ABC you are checking without care for the actual implementation.

For example, say that you have a function F that do something according to the type of the argument, you can check if is a instance of list or tuple or dict or etc directly, and do your job, but that limit you to only have to use those, if you then make your own class that have a similar behavior to say a list, in some case you care about, and want to use it with F, you find it don't work, then you have to modify F to accept your class, but if instead you check against an ABC such modification is unneeded

Now a working example: say that you want a function that give all the elements in even position from a list, then you can do

def even_pos(data):
    if isinstance(data,list):
        return [data[i] for i in range(0,len(data),2)]
    else:
        raise ValueError("only a list")

and use as

>>> test = list(range(20))
>>> even_pos(test)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>

no problem there, but then you realize that a tuple is the same that a list in what a this function concern, you can add that check to the function too, and everything is fine, but then your friend told you he want to use your function but he is using a collections.deque and then your other friend told... see the pattern here? all the object that I mention (list, tuple, deque) have in common the same thing, and can be used in the same way by that example function, and all that behavior is compress in the ABC, so instead of isinstance(data,(list,tuple,collections.deque,...) you only need isinstance(data,abc.Sequence) and the function looks like

from collections import abc
def even_pos(data):
    if isinstance(data,abc.Sequence):
        return [data[i] for i in range(0,len(data),2)]
    else:
        raise ValueError("only a Sequence")

>>> even_pos( list(range(10)) )
[0, 2, 4, 6, 8]
>>> even_pos( tuple(range(10)) )
[0, 2, 4, 6, 8]
>>> even_pos( range(10) )  # in python 3 range don't return a list, but a range object
[0, 2, 4, 6, 8]
>>> even_pos( "asdfghjh" )
['a', 'd', 'g', 'j']
>>> 

Now you don't need to know the actual implementation that is in use, only that it have the behavior that you want

like image 162
Copperfield Avatar answered Nov 02 '22 06:11

Copperfield