ro.py 24 KB

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