[docs] [issue27561] Warn against subclassing builtins, and overriding their methods

Kirk Hansen report at bugs.python.org
Mon Jul 18 09:30:51 EDT 2016

New submission from Kirk Hansen:

I tried subclassing dict, and overriding its __setitem__ and __getitem__ and got some interesting results. See http://stackoverflow.com/questions/38362420/subclassing-dict-dict-update-returns-incorrrect-value-python-bug?noredirect=1#comment64142710_38362420 for an example.

I tried sub-classing UserDict.UserDict and experienced some of the same problems. Eventually, I discovered that subclassing MutableMapping was my best bet.

After an hour or two of searching and reading I discovered that CPython will not call overridden built-in methods of the same object (https://pypy.readthedocs.io/en/latest/cpython_differences.html#subclasses-of-built-in-types). This behaviour could (and did) cause some hard to track down bugs in code. 

I briefly looked at the later versions of python documentation and didn't see a mention of this (sorry if it's there), but python2.7 definitely does not mention this. In fact, python2.7 seems to __encourage__ users to subclass the built-ins (see the note https://docs.python.org/2.7/library/stdtypes.html?highlight=dict#built-in-types). Subclassing dict to __extend__ functionality is great, but there should be a big bad warning when trying to __override__ built-ins like __setitem__ and __getitem__.

assignee: docs at python
components: Documentation
messages: 270754
nosy: Kirk Hansen, docs at python
priority: normal
severity: normal
status: open
title: Warn against subclassing builtins, and overriding their methods
type: enhancement
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6

Python tracker <report at bugs.python.org>

More information about the docs mailing list