From 0da52434253890fdfb20d1f4eb5f661542a627f0 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 7 Jan 2018 11:06:47 +0530 Subject: [PATCH] Add new example: Subclass transitivity --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index b2b71b9..cc6c1ec 100755 --- a/README.md +++ b/README.md @@ -1678,6 +1678,32 @@ SyntaxError: invalid syntax --- +### Subclass relationships + +Suggested by @Lucas-C in [this](https://github.com/satwikkansal/wtfpython/issues/36) issue. + +**Output:** +```py +>>> from collections import Hashable +>>> issubclass(list, object) +True +>>> issubclass(object, Hashable) +True +>>> issubclass(list, Hashable) +False +``` + +The Subclass relationships were expected to be transitive, right? (i.e. if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`) + +#### 💡 Explanation: + +* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. +* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. +* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. +* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). + +--- + ### Let's see if you can guess this? Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.