Python Tip #234 (of 365): Don't inherit from list or dict. You could end up with...

@treyhunner@mastodon.social

Python Tip #234 (of 365):

Don't inherit from list or dict. You could end up with some weird bugs.

Say we make a bi-directional dictionary by customizing __setitem__:

class TwoWayDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, value)
super().__setitem__(value, key)

>>> d = TwoWayDict()
>>> d[3] = 8
>>> d
{3: 8, 8: 3}

And it seems to work... except when it doesn't:

>>> d.update({9: 7})
>>> d
{3: 8, 8: 3, 9: 7}

๐Ÿงต (1/3)

#Python #DailyPythonTip