DVG
DVG

Reputation: 64

Python 2.7: applying str to collections.Counter and collections.defaultdict

collections.Counter and collections.defaultdict are both inherited from dict. So what is the difference between them which causes non-similar output ('class' and 'type')?

import collections

print str(collections.Counter)
print str(collections.defaultdict)

Output:

<class 'collections.Counter'>
<type 'collections.defaultdict'>

Upvotes: 3

Views: 366

Answers (1)

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18477

I'm afraid your answer here boils down to something rather boring: Counter is written in Python and defaultdict is written in C.

Here's collections.py. Notice you can scroll down and find a standard class definition for Counter:

########################################################################
###  Counter
########################################################################

class Counter(dict):
    '''Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.
    ...
    '''

However, defaultdict is imported from _collections:

from _collections import deque, defaultdict

As noted in this answer, that's a built-in extension written in C.

You'll notice you get this same behavior if you string-ify deque (also C) or some other class from collections written in Python:

>>> from collections import deque
>>> str(deque)
"<type 'collections.deque'>"
>>> from collections import OrderedDict
>>> str(OrderedDict)
"<class 'collections.OrderedDict'>"*

Upvotes: 3

Related Questions