Search code examples
pythontypesdefaultdict

How to obtain the type of the values in a defaultdict


I don't know if this question is trivial or not. But after a couple of hours searching I decided to ask it here. Consider the following code:

from collections import defaultdict

d = defaultdict(int)

As far as I know, d only accepts values of type int. Now if I want to create another variable of the same type as the type of the values in d, how I do this? An impossible code but that may help to understand my question is this one:

from collections import defaultdict

d = defaultdict(int)    

a = 1
if type(a) == d.type_of_values:
   print "same type"
else:
   print "different type"

It should print "same type", and I'm inventing the existence of the class member type_of_values, but in this case its value must be int.


Solution

  • You want to look at default_factory:

    >>> from collections import defaultdict
    >>> d = defaultdict(int)
    >>> d
    defaultdict(<type 'int'>, {})
    >>> d.default_factory
    <type 'int'>
    >>> d = defaultdict(list)
    >>> d.default_factory 
    <type 'list'>
    

    (To be honest, to find this out, I simply made a defaultdict, typed dir(d) at the console, and looked for something that seemed promising.)

    Incidentally, it's not true that a defaultdict only accepts values of the default type. For example:

    >>> d = defaultdict(int)
    >>> d[10] = 3+4j
    >>> d
    defaultdict(<type 'int'>, {10: (3+4j)})
    >>> d[30]
    0
    >>> d["fred"]
    0
    

    When you make a default dict, you're really only specifying the factory function which gives values for undefined keys, and nothing more.