diff options
| author | Claudiu Popa <cpopa@cloudbasesolutions.com> | 2014-12-15 20:56:41 +0200 |
|---|---|---|
| committer | Claudiu Popa <cpopa@cloudbasesolutions.com> | 2014-12-15 20:56:41 +0200 |
| commit | e08c8a7149e4d7a2f7846a7203d627fcf3dacfba (patch) | |
| tree | 62fa7374c21df57bd4f547c7333542a07d5dc7c2 | |
| parent | f6e6cff6571d10727148acd8abada8cbd1716cb2 (diff) | |
| download | astroid-git-e08c8a7149e4d7a2f7846a7203d627fcf3dacfba.tar.gz | |
Add a new method to Class nodes, 'mro'.
With this method, the method resolution order of a class can be retrieved.
| -rw-r--r-- | ChangeLog | 3 | ||||
| -rw-r--r-- | astroid/scoped_nodes.py | 42 | ||||
| -rw-r--r-- | astroid/tests/unittest_scoped_nodes.py | 60 |
3 files changed, 103 insertions, 2 deletions
@@ -22,6 +22,9 @@ Change log for the astroid package (used to be astng) the class didn't have slots defined and when it had an empty list of slots, Class.slots returned an empty list. + * Add a new method to Class nodes, 'mro', for obtaining the + the method resolution order of the class. + 2014-11-22 -- 1.3.2 diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 629e3d55..9ba83605 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -36,7 +36,7 @@ from logilab.common.compat import builtins from logilab.common.decorators import cached, cachedproperty from astroid.exceptions import NotFoundError, \ - AstroidBuildingException, InferenceError + AstroidBuildingException, InferenceError, ResolveError from astroid.node_classes import Const, DelName, DelAttr, \ Dict, From, List, Pass, Raise, Return, Tuple, Yield, YieldFrom, \ LookupMixIn, const_factory as cf, unpack_infer, Name, CallFunc @@ -50,6 +50,33 @@ from astroid.manager import AstroidManager ITER_METHODS = ('__iter__', '__getitem__') PY3K = sys.version_info >= (3, 0) +def _c3_merge(sequences): + """Merges MROs in *sequences* to a single MRO using the C3 algorithm. + + Adapted from http://www.python.org/download/releases/2.3/mro/. + + """ + result = [] + while True: + sequences = [s for s in sequences if s] # purge empty sequences + if not sequences: + return result + for s1 in sequences: # find merge candidates among seq heads + candidate = s1[0] + for s2 in sequences: + if candidate in s2[1:]: + candidate = None + break # reject the current head, it appears later + else: + break + if not candidate: + raise ResolveError("Inconsistent hierarchy") + result.append(candidate) + # remove the chosen candidate + for seq in sequences: + if seq[0] == candidate: + del seq[0] + def remove_nodes(func, cls): def wrapper(*args, **kwargs): @@ -1378,3 +1405,16 @@ class Class(Statement, LocalsDictNodeNG, FilterStmtsMixin): return None return [first] + list(slots) + def mro(self): + """Get the method resolution order, using C3 linearization. + + It returns the list of ancestors sorted by the mro. + This will raise `NotImplementedError` for old-style classes, since + they don't have the concept of MRO. + """ + if not self.newstyle: + raise NotImplementedError( + "Could not obtain mro for newstyle classes.") + + bases = list(self.ancestors(recurs=False)) + return _c3_merge([[self]] + [base.mro() for base in bases] + [bases]) diff --git a/astroid/tests/unittest_scoped_nodes.py b/astroid/tests/unittest_scoped_nodes.py index 496b67ff..c9835145 100644 --- a/astroid/tests/unittest_scoped_nodes.py +++ b/astroid/tests/unittest_scoped_nodes.py @@ -25,7 +25,7 @@ import unittest import warnings from astroid import YES, builder, nodes, scoped_nodes, \ - InferenceError, NotFoundError, NoDefault + InferenceError, NotFoundError, NoDefault, ResolveError from astroid.bases import BUILTINS, Instance, BoundMethod, UnboundMethod from astroid import __pkginfo__ from astroid import test_utils @@ -1043,6 +1043,64 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase): [slot.value for slot in tenth_slots], ["a", "c"]) + def assertEqualMro(self, klass, expected_mro): + self.assertEqual( + [member.name for member in klass.mro()], + expected_mro) + + @test_utils.require_version(maxver='3.0') + def test_no_mro_for_old_style(self): + node = test_utils.extract_node(""" + class Old: pass""") + with self.assertRaises(NotImplementedError) as cm: + node.mro() + self.assertEqual(str(cm.exception), "Could not obtain mro for " + "newstyle classes.") + + def test_mro(self): + astroid = test_utils.build_module(""" + class C(object): pass + class D(dict, C): pass + + class A1(object): pass + class B1(A1): pass + class C1(A1): pass + class D1(B1, C1): pass + class E1(C1, B1): pass + class F1(D1, E1): pass + class G1(E1, D1): pass + + class Boat(object): pass + class DayBoat(Boat): pass + class WheelBoat(Boat): pass + class EngineLess(DayBoat): pass + class SmallMultihull(DayBoat): pass + class PedalWheelBoat(EngineLess, WheelBoat): pass + class SmallCatamaran(SmallMultihull): pass + class Pedalo(PedalWheelBoat, SmallCatamaran): pass + + """) + self.assertEqualMro(astroid['D'], ['D', 'dict', 'C', 'object']) + self.assertEqualMro(astroid['D1'], ['D1', 'B1', 'C1', 'A1', 'object']) + self.assertEqualMro(astroid['E1'], ['E1', 'C1', 'B1', 'A1', 'object']) + with self.assertRaises(ResolveError): + astroid['F1'].mro() + with self.assertRaises(ResolveError): + astroid['G1'].mro() + self.assertEqualMro( + astroid['PedalWheelBoat'], + ["PedalWheelBoat", "EngineLess", + "DayBoat", "WheelBoat", "Boat", "object"]) + + self.assertEqualMro( + astroid["SmallCatamaran"], + ["SmallCatamaran", "SmallMultihull", "DayBoat", "Boat", "object"]) + + self.assertEqualMro( + astroid["Pedalo"], + ["Pedalo", "PedalWheelBoat", "EngineLess", "SmallCatamaran", + "SmallMultihull", "DayBoat", "WheelBoat", "Boat", "object"]) + if __name__ == '__main__': unittest.main() |
