Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"dicts would subclass sets, as dicts are essentially sets with values attached"

Such a derivation would violate the Liskov substitution principle. Consider the following with set:

  x = {"one", "two"}
  y = set()
  y.update(x)
  y
It result in y being {'two', 'one'} .

Now, do the same with dict:

  y = dict()
  y.update(x)
This gives the exception: "ValueError: dictionary update sequence element #0 has length 3; 2 is required"

This means that dict cannot be used anywhere that a set can be used, which means it violates the Liskov substitution principle (see https://en.wikipedia.org/wiki/Liskov_substitution_principle ) which means that if covariant methods are needed for good design then dict cannot be a subclass of set.



If dicts did subclass sets, then sets would be dicts whose values are all None. In other words, your last example would be defined as:

    >>> s = {'one', 'two'}
    >>> d = {}
    >>> d.update(s)
    >>> d
    {'two': None, 'one': None}


If sets are dicts with values of None, then they're dicts, not a superclass of dict.


Would s["one"] = 1 raise an exception? Or convert the set into a dict? Or change the sentinel value for all the set elements?

None seem like a good design since it means either the instance change its class on the fly (which Python does support) or that a dict does not act like its parent set object, breaking the is-a relationship most people expect from an OO design.

It seems like the circle/ellipse problem, and the current implementation is the "drop all inheritance relationships" solution to that problem. https://en.wikipedia.org/wiki/Circle-ellipse_problem#Drop_al...


> Would s["one"] = 1 raise an exception?

Sets don't support indexing, so it would still raise an exception. Dicts do, which is an example of them supporting more operations than sets, which is an example of why (if there is to be any subclass relation) dicts are subclasses of sets.

Edit: I suppose there's some confusion about my language above. "then sets would be dicts whose values are all None" could more helpfully read "sets would be equivalent to dicts whose...".


Liskov substitution and meaningful method-mutability forbid any kind of sub-typing relationship.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: