runtime
286 / 500
question 286 Advanced OOP & Design · medium

Compute a method resolution order

Python orders a class's ancestors with the C3 linearization. Write mro(name, bases) that computes it from a table, so you can check a class hierarchy before writing it. bases maps each class name to the list of its direct bases, in order ("object" maps to []). The MRO of a class is the class itself followed by the merge of its bases' MROs and the list of its bases. To merge: repeatedly take the first head (first item) of the lists that doesn't appear in the *tail* (anything after the first item) of any list, append it, and remove it from the front of every list; if no head qualifies, the hierarchy is impossible.

Functionmro(name, bases) → list of class names, starting with name and ending with "object"
RaisesValueError when no consistent order exists, or for a name that isn't in bases
Checkfor real classes your answer matches [c.__name__ for c in C.__mro__]
Examples
callmro('OrderRepository', {'object': [], 'Repository': ['object'], 'AuditMixin': ['object'], 'TimestampMixin': ['object'], 'OrderRepository': ['AuditMixin', 'TimestampMixin', 'Repository']})returns['OrderRepository', 'AuditMixin', 'TimestampMixin', 'Repository', 'object']
callmro('FeaturedSale', {'object': [], 'Listing': ['object'], 'Sale': ['Listing'], 'Featured': ['Listing'], 'FeaturedSale': ['Sale', 'Featured']})returns['FeaturedSale', 'Sale', 'Featured', 'Listing', 'object']
callmro('object', {'object': []})returns['object']
callmro('Bad', {'object': [], 'Repository': ['object'], 'AuditMixin': ['Repository'], 'Bad': ['Repository', 'AuditMixin']})raisesValueError

Loading your progress…

Compute a method resolution order — Python practice · Runtime