Last active
August 8, 2025 21:37
-
-
Save mrbazzan/70d52280d9b132445fa09d1d4600663a to your computer and use it in GitHub Desktop.
Python's Method Resolution Order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # C3 ALGORITHM | |
| # Original paper by Michele Simionato: https://www.python.org/download/releases/2.3/mro/ | |
| # Python3 Implementation. | |
| def merge(seqs): | |
| res = []; | |
| while True: | |
| nonemptyseqs=[seq for seq in seqs if seq] | |
| if not nonemptyseqs: return res | |
| # find merge candidates among seq heads | |
| for seq in nonemptyseqs: | |
| cand = seq[0] | |
| nothead=[s for s in nonemptyseqs if cand in s[1:]] | |
| if nothead: cand=None # reject candidate | |
| else: break | |
| if not cand: raise "Inconsistent hierarchy" | |
| res.append(cand) | |
| for seq in nonemptyseqs: # remove cand | |
| if seq[0] == cand: del seq[0] | |
| def mro(k): | |
| def inner(klass): | |
| b = [] | |
| if not klass: return b | |
| for k in klass: | |
| b += [[k] + inner(k.__bases__)] | |
| return merge(b) | |
| return merge([[k]] + [inner(k.__bases__)] + [list(k.__bases__)]) | |
| class Example: | |
| class D: pass | |
| class E: pass | |
| class F: pass | |
| class X(F): pass | |
| class B(D,E): pass | |
| class C(D,F): pass | |
| class A(B,C): pass | |
| import pprint; pprint.pprint(mro(Example.A)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment