$ ls ~yifei/notes/

do not subclass built-in classes in python

Posted on:

Last modified:

In short, they will not behave what you think they will. you think dict.get in implemented in python, like:

def get(self, key, default=None):
    try:
        return self[key]
    except KeyError:
        return default

However, they dict.get do not call getitem, and they are implemented in c separately, and do not call each other.

so, when you implement geitem, get is not automatically altered! which is very dangerous.

What you need do, subclass collections.abc.Mapping

source:

[1] http://www.kr41.net/2016/03-23-dont_inherit_python_builtin_dict_type.html

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.