Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ro.py 24KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2003 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """
  15. Compute a resolution order for an object and its bases.
  16. .. versionchanged:: 5.0
  17. The resolution order is now based on the same C3 order that Python
  18. uses for classes. In complex instances of multiple inheritance, this
  19. may result in a different ordering.
  20. In older versions, the ordering wasn't required to be C3 compliant,
  21. and for backwards compatibility, it still isn't. If the ordering
  22. isn't C3 compliant (if it is *inconsistent*), zope.interface will
  23. make a best guess to try to produce a reasonable resolution order.
  24. Still (just as before), the results in such cases may be
  25. surprising.
  26. .. rubric:: Environment Variables
  27. Due to the change in 5.0, certain environment variables can be used to control errors
  28. and warnings about inconsistent resolution orders. They are listed in priority order, with
  29. variables at the bottom generally overriding variables above them.
  30. ZOPE_INTERFACE_WARN_BAD_IRO
  31. If this is set to "1", then if there is at least one inconsistent resolution
  32. order discovered, a warning (:class:`InconsistentResolutionOrderWarning`) will
  33. be issued. Use the usual warning mechanisms to control this behaviour. The warning
  34. text will contain additional information on debugging.
  35. ZOPE_INTERFACE_TRACK_BAD_IRO
  36. If this is set to "1", then zope.interface will log information about each
  37. inconsistent resolution order discovered, and keep those details in memory in this module
  38. for later inspection.
  39. ZOPE_INTERFACE_STRICT_IRO
  40. If this is set to "1", any attempt to use :func:`ro` that would produce a non-C3
  41. ordering will fail by raising :class:`InconsistentResolutionOrderError`.
  42. .. important::
  43. ``ZOPE_INTERFACE_STRICT_IRO`` is intended to become the default in the future.
  44. There are two environment variables that are independent.
  45. ZOPE_INTERFACE_LOG_CHANGED_IRO
  46. If this is set to "1", then if the C3 resolution order is different from
  47. the legacy resolution order for any given object, a message explaining the differences
  48. will be logged. This is intended to be used for debugging complicated IROs.
  49. ZOPE_INTERFACE_USE_LEGACY_IRO
  50. If this is set to "1", then the C3 resolution order will *not* be used. The
  51. legacy IRO will be used instead. This is a temporary measure and will be removed in the
  52. future. It is intended to help during the transition.
  53. It implies ``ZOPE_INTERFACE_LOG_CHANGED_IRO``.
  54. .. rubric:: Debugging Behaviour Changes in zope.interface 5
  55. Most behaviour changes from zope.interface 4 to 5 are related to
  56. inconsistent resolution orders. ``ZOPE_INTERFACE_STRICT_IRO`` is the
  57. most effective tool to find such inconsistent resolution orders, and
  58. we recommend running your code with this variable set if at all
  59. possible. Doing so will ensure that all interface resolution orders
  60. are consistent, and if they're not, will immediately point the way to
  61. where this is violated.
  62. Occasionally, however, this may not be enough. This is because in some
  63. cases, a C3 ordering can be found (the resolution order is fully
  64. consistent) that is substantially different from the ad-hoc legacy
  65. ordering. In such cases, you may find that you get an unexpected value
  66. returned when adapting one or more objects to an interface. To debug
  67. this, *also* enable ``ZOPE_INTERFACE_LOG_CHANGED_IRO`` and examine the
  68. output. The main thing to look for is changes in the relative
  69. positions of interfaces for which there are registered adapters.
  70. """
  71. __docformat__ = 'restructuredtext'
  72. __all__ = [
  73. 'ro',
  74. 'InconsistentResolutionOrderError',
  75. 'InconsistentResolutionOrderWarning',
  76. ]
  77. __logger = None
  78. def _logger():
  79. global __logger # pylint:disable=global-statement
  80. if __logger is None:
  81. import logging
  82. __logger = logging.getLogger(__name__)
  83. return __logger
  84. def _legacy_mergeOrderings(orderings):
  85. """Merge multiple orderings so that within-ordering order is preserved
  86. Orderings are constrained in such a way that if an object appears
  87. in two or more orderings, then the suffix that begins with the
  88. object must be in both orderings.
  89. For example:
  90. >>> _mergeOrderings([
  91. ... ['x', 'y', 'z'],
  92. ... ['q', 'z'],
  93. ... [1, 3, 5],
  94. ... ['z']
  95. ... ])
  96. ['x', 'y', 'q', 1, 3, 5, 'z']
  97. """
  98. seen = set()
  99. result = []
  100. for ordering in reversed(orderings):
  101. for o in reversed(ordering):
  102. if o not in seen:
  103. seen.add(o)
  104. result.insert(0, o)
  105. return result
  106. def _legacy_flatten(begin):
  107. result = [begin]
  108. i = 0
  109. for ob in iter(result):
  110. i += 1
  111. # The recursive calls can be avoided by inserting the base classes
  112. # into the dynamically growing list directly after the currently
  113. # considered object; the iterator makes sure this will keep working
  114. # in the future, since it cannot rely on the length of the list
  115. # by definition.
  116. result[i:i] = ob.__bases__
  117. return result
  118. def _legacy_ro(ob):
  119. return _legacy_mergeOrderings([_legacy_flatten(ob)])
  120. ###
  121. # Compare base objects using identity, not equality. This matches what
  122. # the CPython MRO algorithm does, and is *much* faster to boot: that,
  123. # plus some other small tweaks makes the difference between 25s and 6s
  124. # in loading 446 plone/zope interface.py modules (1925 InterfaceClass,
  125. # 1200 Implements, 1100 ClassProvides objects)
  126. ###
  127. class InconsistentResolutionOrderWarning(PendingDeprecationWarning):
  128. """
  129. The warning issued when an invalid IRO is requested.
  130. """
  131. class InconsistentResolutionOrderError(TypeError):
  132. """
  133. The error raised when an invalid IRO is requested in strict mode.
  134. """
  135. def __init__(self, c3, base_tree_remaining):
  136. self.C = c3.leaf
  137. base_tree = c3.base_tree
  138. self.base_ros = {
  139. base: base_tree[i + 1]
  140. for i, base in enumerate(self.C.__bases__)
  141. }
  142. # Unfortunately, this doesn't necessarily directly match
  143. # up to any transformation on C.__bases__, because
  144. # if any were fully used up, they were removed already.
  145. self.base_tree_remaining = base_tree_remaining
  146. TypeError.__init__(self)
  147. def __str__(self):
  148. import pprint
  149. return "{}: For object {!r}.\nBase ROs:\n{}\nConflict Location:\n{}".format(
  150. self.__class__.__name__,
  151. self.C,
  152. pprint.pformat(self.base_ros),
  153. pprint.pformat(self.base_tree_remaining),
  154. )
  155. class _NamedBool(int): # cannot actually inherit bool
  156. def __new__(cls, val, name):
  157. inst = super(cls, _NamedBool).__new__(cls, val)
  158. inst.__name__ = name
  159. return inst
  160. class _ClassBoolFromEnv:
  161. """
  162. Non-data descriptor that reads a transformed environment variable
  163. as a boolean, and caches the result in the class.
  164. """
  165. def __get__(self, inst, klass):
  166. import os
  167. for cls in klass.__mro__:
  168. my_name = None
  169. for k in dir(klass):
  170. if k in cls.__dict__ and cls.__dict__[k] is self:
  171. my_name = k
  172. break
  173. if my_name is not None:
  174. break
  175. else: # pragma: no cover
  176. raise RuntimeError("Unable to find self")
  177. env_name = 'ZOPE_INTERFACE_' + my_name
  178. val = os.environ.get(env_name, '') == '1'
  179. val = _NamedBool(val, my_name)
  180. setattr(klass, my_name, val)
  181. setattr(klass, 'ORIG_' + my_name, self)
  182. return val
  183. class _StaticMRO:
  184. # A previously resolved MRO, supplied by the caller.
  185. # Used in place of calculating it.
  186. had_inconsistency = None # We don't know...
  187. def __init__(self, C, mro):
  188. self.leaf = C
  189. self.__mro = tuple(mro)
  190. def mro(self):
  191. return list(self.__mro)
  192. class C3:
  193. # Holds the shared state during computation of an MRO.
  194. @staticmethod
  195. def resolver(C, strict, base_mros):
  196. strict = strict if strict is not None else C3.STRICT_IRO
  197. factory = C3
  198. if strict:
  199. factory = _StrictC3
  200. elif C3.TRACK_BAD_IRO:
  201. factory = _TrackingC3
  202. memo = {}
  203. base_mros = base_mros or {}
  204. for base, mro in base_mros.items():
  205. assert base in C.__bases__
  206. memo[base] = _StaticMRO(base, mro)
  207. return factory(C, memo)
  208. __mro = None
  209. __legacy_ro = None
  210. direct_inconsistency = False
  211. def __init__(self, C, memo):
  212. self.leaf = C
  213. self.memo = memo
  214. kind = self.__class__
  215. base_resolvers = []
  216. for base in C.__bases__:
  217. if base not in memo:
  218. resolver = kind(base, memo)
  219. memo[base] = resolver
  220. base_resolvers.append(memo[base])
  221. self.base_tree = [
  222. [C]
  223. ] + [
  224. memo[base].mro() for base in C.__bases__
  225. ] + [
  226. list(C.__bases__)
  227. ]
  228. self.bases_had_inconsistency = any(base.had_inconsistency for base in base_resolvers)
  229. if len(C.__bases__) == 1:
  230. self.__mro = [C] + memo[C.__bases__[0]].mro()
  231. @property
  232. def had_inconsistency(self):
  233. return self.direct_inconsistency or self.bases_had_inconsistency
  234. @property
  235. def legacy_ro(self):
  236. if self.__legacy_ro is None:
  237. self.__legacy_ro = tuple(_legacy_ro(self.leaf))
  238. return list(self.__legacy_ro)
  239. TRACK_BAD_IRO = _ClassBoolFromEnv()
  240. STRICT_IRO = _ClassBoolFromEnv()
  241. WARN_BAD_IRO = _ClassBoolFromEnv()
  242. LOG_CHANGED_IRO = _ClassBoolFromEnv()
  243. USE_LEGACY_IRO = _ClassBoolFromEnv()
  244. BAD_IROS = ()
  245. def _warn_iro(self):
  246. if not self.WARN_BAD_IRO:
  247. # For the initial release, one must opt-in to see the warning.
  248. # In the future (2021?) seeing at least the first warning will
  249. # be the default
  250. return
  251. import warnings
  252. warnings.warn(
  253. "An inconsistent resolution order is being requested. "
  254. "(Interfaces should follow the Python class rules known as C3.) "
  255. "For backwards compatibility, zope.interface will allow this, "
  256. "making the best guess it can to produce as meaningful an order as possible. "
  257. "In the future this might be an error. Set the warning filter to error, or set "
  258. "the environment variable 'ZOPE_INTERFACE_TRACK_BAD_IRO' to '1' and examine "
  259. "ro.C3.BAD_IROS to debug, or set 'ZOPE_INTERFACE_STRICT_IRO' to raise exceptions.",
  260. InconsistentResolutionOrderWarning,
  261. )
  262. @staticmethod
  263. def _can_choose_base(base, base_tree_remaining):
  264. # From C3:
  265. # nothead = [s for s in nonemptyseqs if cand in s[1:]]
  266. for bases in base_tree_remaining:
  267. if not bases or bases[0] is base:
  268. continue
  269. for b in bases:
  270. if b is base:
  271. return False
  272. return True
  273. @staticmethod
  274. def _nonempty_bases_ignoring(base_tree, ignoring):
  275. return list(filter(None, [
  276. [b for b in bases if b is not ignoring]
  277. for bases
  278. in base_tree
  279. ]))
  280. def _choose_next_base(self, base_tree_remaining):
  281. """
  282. Return the next base.
  283. The return value will either fit the C3 constraints or be our best
  284. guess about what to do. If we cannot guess, this may raise an exception.
  285. """
  286. base = self._find_next_C3_base(base_tree_remaining)
  287. if base is not None:
  288. return base
  289. return self._guess_next_base(base_tree_remaining)
  290. def _find_next_C3_base(self, base_tree_remaining):
  291. """
  292. Return the next base that fits the constraints, or ``None`` if there isn't one.
  293. """
  294. for bases in base_tree_remaining:
  295. base = bases[0]
  296. if self._can_choose_base(base, base_tree_remaining):
  297. return base
  298. return None
  299. class _UseLegacyRO(Exception):
  300. pass
  301. def _guess_next_base(self, base_tree_remaining):
  302. # Narf. We may have an inconsistent order (we won't know for
  303. # sure until we check all the bases). Python cannot create
  304. # classes like this:
  305. #
  306. # class B1:
  307. # pass
  308. # class B2(B1):
  309. # pass
  310. # class C(B1, B2): # -> TypeError; this is like saying C(B1, B2, B1).
  311. # pass
  312. #
  313. # However, older versions of zope.interface were fine with this order.
  314. # A good example is ``providedBy(IOError())``. Because of the way
  315. # ``classImplements`` works, it winds up with ``__bases__`` ==
  316. # ``[IEnvironmentError, IIOError, IOSError, <implementedBy Exception>]``
  317. # (on Python 3). But ``IEnvironmentError`` is a base of both ``IIOError``
  318. # and ``IOSError``. Previously, we would get a resolution order of
  319. # ``[IIOError, IOSError, IEnvironmentError, IStandardError, IException, Interface]``
  320. # but the standard Python algorithm would forbid creating that order entirely.
  321. # Unlike Python's MRO, we attempt to resolve the issue. A few
  322. # heuristics have been tried. One was:
  323. #
  324. # Strip off the first (highest priority) base of each direct
  325. # base one at a time and seeing if we can come to an agreement
  326. # with the other bases. (We're trying for a partial ordering
  327. # here.) This often resolves cases (such as the IOSError case
  328. # above), and frequently produces the same ordering as the
  329. # legacy MRO did. If we looked at all the highest priority
  330. # bases and couldn't find any partial ordering, then we strip
  331. # them *all* out and begin the C3 step again. We take care not
  332. # to promote a common root over all others.
  333. #
  334. # If we only did the first part, stripped off the first
  335. # element of the first item, we could resolve simple cases.
  336. # But it tended to fail badly. If we did the whole thing, it
  337. # could be extremely painful from a performance perspective
  338. # for deep/wide things like Zope's OFS.SimpleItem.Item. Plus,
  339. # anytime you get ExtensionClass.Base into the mix, you're
  340. # likely to wind up in trouble, because it messes with the MRO
  341. # of classes. Sigh.
  342. #
  343. # So now, we fall back to the old linearization (fast to compute).
  344. self._warn_iro()
  345. self.direct_inconsistency = InconsistentResolutionOrderError(self, base_tree_remaining)
  346. raise self._UseLegacyRO
  347. def _merge(self):
  348. # Returns a merged *list*.
  349. result = self.__mro = []
  350. base_tree_remaining = self.base_tree
  351. base = None
  352. while 1:
  353. # Take last picked base out of the base tree wherever it is.
  354. # This differs slightly from the standard Python MRO and is needed
  355. # because we have no other step that prevents duplicates
  356. # from coming in (e.g., in the inconsistent fallback path)
  357. base_tree_remaining = self._nonempty_bases_ignoring(base_tree_remaining, base)
  358. if not base_tree_remaining:
  359. return result
  360. try:
  361. base = self._choose_next_base(base_tree_remaining)
  362. except self._UseLegacyRO:
  363. self.__mro = self.legacy_ro
  364. return self.legacy_ro
  365. result.append(base)
  366. def mro(self):
  367. if self.__mro is None:
  368. self.__mro = tuple(self._merge())
  369. return list(self.__mro)
  370. class _StrictC3(C3):
  371. __slots__ = ()
  372. def _guess_next_base(self, base_tree_remaining):
  373. raise InconsistentResolutionOrderError(self, base_tree_remaining)
  374. class _TrackingC3(C3):
  375. __slots__ = ()
  376. def _guess_next_base(self, base_tree_remaining):
  377. import traceback
  378. bad_iros = C3.BAD_IROS
  379. if self.leaf not in bad_iros:
  380. if bad_iros == ():
  381. import weakref
  382. # This is a race condition, but it doesn't matter much.
  383. bad_iros = C3.BAD_IROS = weakref.WeakKeyDictionary()
  384. bad_iros[self.leaf] = t = (
  385. InconsistentResolutionOrderError(self, base_tree_remaining),
  386. traceback.format_stack()
  387. )
  388. _logger().warning("Tracking inconsistent IRO: %s", t[0])
  389. return C3._guess_next_base(self, base_tree_remaining)
  390. class _ROComparison:
  391. # Exists to compute and print a pretty string comparison
  392. # for differing ROs.
  393. # Since we're used in a logging context, and may actually never be printed,
  394. # this is a class so we can defer computing the diff until asked.
  395. # Components we use to build up the comparison report
  396. class Item:
  397. prefix = ' '
  398. def __init__(self, item):
  399. self.item = item
  400. def __str__(self):
  401. return "{}{}".format(
  402. self.prefix,
  403. self.item,
  404. )
  405. class Deleted(Item):
  406. prefix = '- '
  407. class Inserted(Item):
  408. prefix = '+ '
  409. Empty = str
  410. class ReplacedBy: # pragma: no cover
  411. prefix = '- '
  412. suffix = ''
  413. def __init__(self, chunk, total_count):
  414. self.chunk = chunk
  415. self.total_count = total_count
  416. def __iter__(self):
  417. lines = [
  418. self.prefix + str(item) + self.suffix
  419. for item in self.chunk
  420. ]
  421. while len(lines) < self.total_count:
  422. lines.append('')
  423. return iter(lines)
  424. class Replacing(ReplacedBy):
  425. prefix = "+ "
  426. suffix = ''
  427. _c3_report = None
  428. _legacy_report = None
  429. def __init__(self, c3, c3_ro, legacy_ro):
  430. self.c3 = c3
  431. self.c3_ro = c3_ro
  432. self.legacy_ro = legacy_ro
  433. def __move(self, from_, to_, chunk, operation):
  434. for x in chunk:
  435. to_.append(operation(x))
  436. from_.append(self.Empty())
  437. def _generate_report(self):
  438. if self._c3_report is None:
  439. import difflib
  440. # The opcodes we get describe how to turn 'a' into 'b'. So
  441. # the old one (legacy) needs to be first ('a')
  442. matcher = difflib.SequenceMatcher(None, self.legacy_ro, self.c3_ro)
  443. # The reports are equal length sequences. We're going for a
  444. # side-by-side diff.
  445. self._c3_report = c3_report = []
  446. self._legacy_report = legacy_report = []
  447. for opcode, leg1, leg2, c31, c32 in matcher.get_opcodes():
  448. c3_chunk = self.c3_ro[c31:c32]
  449. legacy_chunk = self.legacy_ro[leg1:leg2]
  450. if opcode == 'equal':
  451. # Guaranteed same length
  452. c3_report.extend(self.Item(x) for x in c3_chunk)
  453. legacy_report.extend(self.Item(x) for x in legacy_chunk)
  454. if opcode == 'delete':
  455. # Guaranteed same length
  456. assert not c3_chunk
  457. self.__move(c3_report, legacy_report, legacy_chunk, self.Deleted)
  458. if opcode == 'insert':
  459. # Guaranteed same length
  460. assert not legacy_chunk
  461. self.__move(legacy_report, c3_report, c3_chunk, self.Inserted)
  462. if opcode == 'replace': # pragma: no cover (How do you make it output this?)
  463. # Either side could be longer.
  464. chunk_size = max(len(c3_chunk), len(legacy_chunk))
  465. c3_report.extend(self.Replacing(c3_chunk, chunk_size))
  466. legacy_report.extend(self.ReplacedBy(legacy_chunk, chunk_size))
  467. return self._c3_report, self._legacy_report
  468. @property
  469. def _inconsistent_label(self):
  470. inconsistent = []
  471. if self.c3.direct_inconsistency:
  472. inconsistent.append('direct')
  473. if self.c3.bases_had_inconsistency:
  474. inconsistent.append('bases')
  475. return '+'.join(inconsistent) if inconsistent else 'no'
  476. def __str__(self):
  477. c3_report, legacy_report = self._generate_report()
  478. assert len(c3_report) == len(legacy_report)
  479. left_lines = [str(x) for x in legacy_report]
  480. right_lines = [str(x) for x in c3_report]
  481. # We have the same number of lines in the report; this is not
  482. # necessarily the same as the number of items in either RO.
  483. assert len(left_lines) == len(right_lines)
  484. padding = ' ' * 2
  485. max_left = max(len(x) for x in left_lines)
  486. max_right = max(len(x) for x in right_lines)
  487. left_title = 'Legacy RO (len={})'.format(len(self.legacy_ro))
  488. right_title = 'C3 RO (len={}; inconsistent={})'.format(
  489. len(self.c3_ro),
  490. self._inconsistent_label,
  491. )
  492. lines = [
  493. (padding + left_title.ljust(max_left) + padding + right_title.ljust(max_right)),
  494. padding + '=' * (max_left + len(padding) + max_right)
  495. ]
  496. lines += [
  497. padding + left.ljust(max_left) + padding + right
  498. for left, right in zip(left_lines, right_lines)
  499. ]
  500. return '\n'.join(lines)
  501. # Set to `Interface` once it is defined. This is used to
  502. # avoid logging false positives about changed ROs.
  503. _ROOT = None
  504. def ro(C, strict=None, base_mros=None, log_changed_ro=None, use_legacy_ro=None):
  505. """
  506. ro(C) -> list
  507. Compute the precedence list (mro) according to C3.
  508. :return: A fresh `list` object.
  509. .. versionchanged:: 5.0.0
  510. Add the *strict*, *log_changed_ro* and *use_legacy_ro*
  511. keyword arguments. These are provisional and likely to be
  512. removed in the future. They are most useful for testing.
  513. """
  514. # The ``base_mros`` argument is for internal optimization and
  515. # not documented.
  516. resolver = C3.resolver(C, strict, base_mros)
  517. mro = resolver.mro()
  518. log_changed = log_changed_ro if log_changed_ro is not None else resolver.LOG_CHANGED_IRO
  519. use_legacy = use_legacy_ro if use_legacy_ro is not None else resolver.USE_LEGACY_IRO
  520. if log_changed or use_legacy:
  521. legacy_ro = resolver.legacy_ro
  522. assert isinstance(legacy_ro, list)
  523. assert isinstance(mro, list)
  524. changed = legacy_ro != mro
  525. if changed:
  526. # Did only Interface move? The fix for issue #8 made that
  527. # somewhat common. It's almost certainly not a problem, though,
  528. # so allow ignoring it.
  529. legacy_without_root = [x for x in legacy_ro if x is not _ROOT]
  530. mro_without_root = [x for x in mro if x is not _ROOT]
  531. changed = legacy_without_root != mro_without_root
  532. if changed:
  533. comparison = _ROComparison(resolver, mro, legacy_ro)
  534. _logger().warning(
  535. "Object %r has different legacy and C3 MROs:\n%s",
  536. C, comparison
  537. )
  538. if resolver.had_inconsistency and legacy_ro == mro:
  539. comparison = _ROComparison(resolver, mro, legacy_ro)
  540. _logger().warning(
  541. "Object %r had inconsistent IRO and used the legacy RO:\n%s"
  542. "\nInconsistency entered at:\n%s",
  543. C, comparison, resolver.direct_inconsistency
  544. )
  545. if use_legacy:
  546. return legacy_ro
  547. return mro
  548. def is_consistent(C):
  549. """
  550. Check if the resolution order for *C*, as computed by :func:`ro`, is consistent
  551. according to C3.
  552. """
  553. return not C3.resolver(C, False, None).had_inconsistency