How is defaultdict setup as a subclass of dict in _collectionsmodule.c

New to C/Python extensions and I have been going through the default dict source code and stumbled upon the fact that the __missing__ function for default dict is called by the __getitem__ upon doing a check with PyDict_CheckExact.

Is default dict automatically considered a subclass by virtue of having a dictionary in its type definition and __missing__ function? If not, which part of defaultdict’s code defines it to be deriving dict? How does inheritance work between objects defined in C?

Thanks

A confusion I am having is we haven’t defined a __getitem__ method for default dict which I would imagine would call the dictionary’s getitem method

Is default dict automatically considered a subclass by virtue of having a dictionary and missing function?

No, that is not the cause. The base class has to be declared explicitly.

For defaultdict, the explicit declaration is hard to find. It is not in the C code for the class. Instead, it is in the module initialization code:

ADD_TYPE(module, &defdict_spec, state->defdict_type, &PyDict_Type);

The ADD_TYPE line calls PyType_FromMetaclass which fills in the DEFERRED_ADDRESS used for tp_base.

The best way to learn how to make a subclass in a C extension is to read Modules/xxsubtype.c. That example is more straightforward than trying to read the indirect setup for defaultdict.

1 Like