trouble subclassing str

Paul McGuire ptmcg at austin.rr.com
Fri Jun 24 14:34:43 EDT 2005


Look at the related post, on keeping key-key pairs in a dictionary.
Based on our discussion in this thread, I created a subclass of dict
called SymmetricDict, that, when storing symDict["A"] = 1, implicitly
saves the backward looking symDict[1] = "A".

I chose to inherit from dict, in part just to see what it would look
like.  In doing so, SymmetricDict automagically gets methods such as
keys(), values(), items(), contains(), and support for len, "key in
dict", etc.  However, I think SymmetricDict breaks (or at least bends)
LSP, in that there are some cases where SymmetricDict has some
surprising non-dict behavior.  For instance, if I do:

   d = dict()
   d["A"] = 1
   d["B"] = 1
   print d.keys()

I get ["A", "B"].  But a SymmetricDict is rather strange.

   sd = SymmetricDict()
   sd["A"] = 1
   sd["B"] = 1
   print sd.keys()

gives ["B",1].  The second assignment wiped out the association of "A"
to 1.  (This reminds me of some maddening O-O discussions I used to
have at a former place of employment, in which one developer cited
similar behavior for not having Square inherit from Rectangle - calling
Square.setWidth() would have to implicitly call setHeight() and vice
versa, in order to maintain its squarishness, and thereby broke Liskov.
I withdrew from the debate, citing lack of context that would have
helped resolve how things should go.  At best, you can *probably* say
that both inherit from Shape, and can be drawn, have an area, a
bounding rectangle, etc., but not either inherits from the other.
Unless I'm mistaken, I think Robert Martin has some discussion on this
example also.)

So in sum, I'd say that I would be comfortable having SymmetricDict
extend dict *in my own code*, but that such a beast probably should
*not* be part of the standard Python distribution, in whose scope the
non-dictishness of SymmetricDict cannot be predicted.  (And maybe this
gives us some clue about the difficulty of deciding what and what not
to put in to the Python language and libs.)

-- Paul




More information about the Python-list mailing list