o $ x`^@sdZddlmZdZgdZdaddZdd Zd d Zd d Z Gddde Z Gddde Z GdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZdZd$d d!Zd"d#ZdS)%aj Compute a resolution order for an object and its bases. .. versionchanged:: 5.0 The resolution order is now based on the same C3 order that Python uses for classes. In complex instances of multiple inheritance, this may result in a different ordering. In older versions, the ordering wasn't required to be C3 compliant, and for backwards compatibility, it still isn't. If the ordering isn't C3 compliant (if it is *inconsistent*), zope.interface will make a best guess to try to produce a reasonable resolution order. Still (just as before), the results in such cases may be surprising. .. rubric:: Environment Variables Due to the change in 5.0, certain environment variables can be used to control errors and warnings about inconsistent resolution orders. They are listed in priority order, with variables at the bottom generally overriding variables above them. ZOPE_INTERFACE_WARN_BAD_IRO If this is set to "1", then if there is at least one inconsistent resolution order discovered, a warning (:class:`InconsistentResolutionOrderWarning`) will be issued. Use the usual warning mechanisms to control this behaviour. The warning text will contain additional information on debugging. ZOPE_INTERFACE_TRACK_BAD_IRO If this is set to "1", then zope.interface will log information about each inconsistent resolution order discovered, and keep those details in memory in this module for later inspection. ZOPE_INTERFACE_STRICT_IRO If this is set to "1", any attempt to use :func:`ro` that would produce a non-C3 ordering will fail by raising :class:`InconsistentResolutionOrderError`. .. important:: ``ZOPE_INTERFACE_STRICT_IRO`` is intended to become the default in the future. There are two environment variables that are independent. ZOPE_INTERFACE_LOG_CHANGED_IRO If this is set to "1", then if the C3 resolution order is different from the legacy resolution order for any given object, a message explaining the differences will be logged. This is intended to be used for debugging complicated IROs. ZOPE_INTERFACE_USE_LEGACY_IRO If this is set to "1", then the C3 resolution order will *not* be used. The legacy IRO will be used instead. This is a temporary measure and will be removed in the future. It is intended to help during the transition. It implies ``ZOPE_INTERFACE_LOG_CHANGED_IRO``. .. rubric:: Debugging Behaviour Changes in zope.interface 5 Most behaviour changes from zope.interface 4 to 5 are related to inconsistent resolution orders. ``ZOPE_INTERFACE_STRICT_IRO`` is the most effective tool to find such inconsistent resolution orders, and we recommend running your code with this variable set if at all possible. Doing so will ensure that all interface resolution orders are consistent, and if they're not, will immediately point the way to where this is violated. Occasionally, however, this may not be enough. This is because in some cases, a C3 ordering can be found (the resolution order is fully consistent) that is substantially different from the ad-hoc legacy ordering. In such cases, you may find that you get an unexpected value returned when adapting one or more objects to an interface. To debug this, *also* enable ``ZOPE_INTERFACE_LOG_CHANGED_IRO`` and examine the output. The main thing to look for is changes in the relative positions of interfaces for which there are registered adapters. )print_functionrestructuredtext)ro InconsistentResolutionOrderError"InconsistentResolutionOrderWarningNcCstdur ddl}|tatS)Nr)__loggerlogging getLogger__name__)rr 3/usr/lib/python3/dist-packages/zope/interface/ro.py_logger^s r cCsHt}g}t|D]}t|D]}||vr |||d|qq |S)aMerge multiple orderings so that within-ordering order is preserved Orderings are constrained in such a way that if an object appears in two or more orderings, then the suffix that begins with the object must be in both orderings. For example: >>> _mergeOrderings([ ... ['x', 'y', 'z'], ... ['q', 'z'], ... [1, 3, 5], ... ['z'] ... ]) ['x', 'y', 'q', 1, 3, 5, 'z'] r)setreversedaddinsert) orderingsseenresultorderingor r r _legacy_mergeOrderingses    rcCs2|g}d}t|D] }|d7}|j|||<q |S)Nr)iter __bases__)beginriobr r r _legacy_flattens  rcCstt|gSN)rr)rr r r _legacy_rosr c@eZdZdZdS)rz> The warning issued when an invalid IRO is requested. N)r __module__ __qualname____doc__r r r r rrc@ eZdZdZddZddZdS)rzK The error raised when an invalid IRO is requested in strict mode. cs>|j|_|jfddt|jjD|_||_t|dS)Ncsi|] \}}||dqS)rr ).0rbase base_treer r s z=InconsistentResolutionOrderError.__init__..) leafCr* enumeraterbase_rosbase_tree_remaining TypeError__init__)selfc3r0r r)r r2s  z)InconsistentResolutionOrderError.__init__cCs.ddl}d|jj|j||j||jfS)Nrz5%s: For object %r. Base ROs: %s Conflict Location: %s)pprint __class__r r-pformatr/r0)r3r5r r r __str__s  z(InconsistentResolutionOrderError.__str__N)r r"r#r$r2r8r r r r rs rcseZdZfddZZS) _NamedBoolcst|t||}||_|Sr)superr9__new__r )clsvalnameinstr6r r r;sz_NamedBool.__new__)r r"r#r; __classcell__r r r@r r9sr9c@eZdZdZddZdS)_ClassBoolFromEnvz Non-data descriptor that reads a transformed environment variable as a boolean, and caches the result in the class. c Csddl}|jD]!}d}t|D]}||jvr!|j||ur!|}nq|dur(nqtdd|}|j|ddk}t||}t|||t|d|||S)NrzUnable to find selfZOPE_INTERFACE_1ORIG_) os__mro__dir__dict__ RuntimeErrorenvirongetr9setattr) r3r?klassrHr<my_namekenv_namer=r r r __get__s$    z_ClassBoolFromEnv.__get__N)r r"r#r$rTr r r r rCs rCc@s eZdZdZddZddZdS) _StaticMRONcCs||_t||_dSr)r,tuple_StaticMRO__mro)r3r-mror r r r2sz_StaticMRO.__init__cCs t|jSr)listrWr3r r r rX z_StaticMRO.mro)r r"r#had_inconsistencyr2rXr r r r rUs rUc@seZdZeddZdZdZdZddZe ddZ e d d Z e Z e Ze Ze Ze Zd Zd d ZeddZeddZddZddZGdddeZddZddZddZdS)C3cCsn|dur|ntj}t}|rt}ntjrt}i}|pi}|D]\}}||jvs*Jt||||<q|||Sr)r] STRICT_IRO _StrictC3 TRACK_BAD_IRO _TrackingC3itemsrrU)r-strict base_mrosfactorymemor(rXr r r resolvers z C3.resolverNFcs||_|_|j}g}|jD]}|vr||}||<||q|ggfdd|jDt|jg|_tdd|D|_t |jdkrZ|g|jd |_ dSdS)Ncsg|]}|qSr )rXr'r(rfr r s zC3.__init__..css|]}|jVqdSr)r\rhr r r szC3.__init__..rr) r,rfr6rappendrYr*anybases_had_inconsistencylenrX_C3__mro)r3r-rfkindbase_resolversr(rgr rir r2s,   z C3.__init__cCs |jp|jSr)direct_inconsistencyrnrZr r r r\s zC3.had_inconsistencycCs$|jdur tt|j|_t|jSr)_C3__legacy_rorVr r,rYrZr r r legacy_ro#s  z C3.legacy_ror cCs"|jsdSddl}|dtdS)NraAn inconsistent resolution order is being requested. (Interfaces should follow the Python class rules known as C3.) For backwards compatibility, zope.interface will allow this, making the best guess it can to produce as meaningful an order as possible. In the future this might be an error. Set the warning filter to error, or set the environment variable 'ZOPE_INTERFACE_TRACK_BAD_IRO' to '1' and examine ro.C3.BAD_IROS to debug, or set 'ZOPE_INTERFACE_STRICT_IRO' to raise exceptions.) WARN_BAD_IROwarningswarnr)r3rwr r r _warn_iro0sz C3._warn_irocCs:|D]}|r |d|ur q|D] }||urdSqqdS)NrFTr )r(r0basesbr r r _can_choose_baseBszC3._can_choose_basecsttdfdd|DS)Ncsg|] }fdd|DqS)csg|]}|ur|qSr r )r'r{ignoringr r rjRz:C3._nonempty_bases_ignoring...r )r'rzr}r r rjQsz/C3._nonempty_bases_ignoring..)rYfilter)r*r~r r}r _nonempty_bases_ignoringOs zC3._nonempty_bases_ignoringcCs ||}|dur |S||S)z Return the next base. The return value will either fit the C3 constraints or be our best guess about what to do. If we cannot guess, this may raise an exception. N)_find_next_C3_base_guess_next_base)r3r0r(r r r _choose_next_baseWs  zC3._choose_next_basecCs*|D]}|d}|||r|SqdS)za Return the next base that fits the constraints, or ``None`` if there isn't one. rN)r|)r3r0rzr(r r r rcs  zC3._find_next_C3_basec@s eZdZdS)zC3._UseLegacyRON)r r"r#r r r r _UseLegacyROmsrcCs|t|||_|jr)ryrrsrr3r0r r r rps, zC3._guess_next_basecCshg}|_|j}d} |||}|s|Sz||}Wn|jy-|j|_|jYSw||q r)rpr*rrrrurl)r3rr0r(r r r _merges    z C3._mergecCs"|jdur t||_t|jSr)rprVrrYrZr r r rXs  zC3.mro)r r"r# staticmethodrgrprtrsr2propertyr\rurCr`r^rvLOG_CHANGED_IROUSE_LEGACY_IROBAD_IROSryr|rrr ExceptionrrrrXr r r r r]s8       0 r]c@rB)r_r cCs t||r)rrr r r rr[z_StrictC3._guess_next_baseNr r"r# __slots__rr r r r r_ r_c@rB)rar cCspddl}tj}|j|vr2|dkrddl}|}t_t|||f||j<}t d|dt ||S)Nrr zTracking inconsistent IRO: %s) tracebackr]rr,weakrefWeakKeyDictionaryr format_stackr warningr)r3r0rbad_irosrtr r r rs  z_TrackingC3._guess_next_baseNrr r r r rarrac@seZdZGdddeZGdddeZGdddeZeZGdddeZ Gd d d e Z d Z d Z d d Z ddZddZeddZddZd S) _ROComparisonc@r&)z_ROComparison.Item cCs ||_dSr)item)r3rr r r r2r[z_ROComparison.Item.__init__cCsd|j|jfS)Nz%s%s)prefixrrZr r r r8sz_ROComparison.Item.__str__N)r r"r#rr2r8r r r r Items rc@r!)z_ROComparison.Deleted- Nr r"r#rr r r r Deletedr%rc@r!)z_ROComparison.Inserted+ Nrr r r r Insertedr%rc@s$eZdZdZdZddZddZdS)z_ROComparison.ReplacedByrrEcCs||_||_dSr)chunk total_count)r3rrr r r r2s z!_ROComparison.ReplacedBy.__init__csBfddjD}t|jkr|dt|jkst|S)Ncs g|] }jt|jqSr )rstrsuffix)r'rrZr r rjsz5_ROComparison.ReplacedBy.__iter__..rE)rrorrlr)r3linesr rZr __iter__s  z!_ROComparison.ReplacedBy.__iter__N)r r"r#rrr2rr r r r ReplacedBys  rc@seZdZdZdZdS)z_ROComparison.ReplacingrrEN)r r"r#rrr r r r ReplacingsrNcCs||_||_||_dSr)r4c3_roru)r3r4rrur r r r2s z_ROComparison.__init__cCs*|D]}|||||qdSr)rlEmpty)r3from_to_r operationxr r r __move sz_ROComparison.__movec s2jdurddl}|djj}g_}g_}|D]r\}}}}} j|| } j||} |dkrQ|fdd| D|fdd| D|dkrb| rYJ||| j |dkrs| rjJ||| j |dkrt t | t | } | | | || | q jjfS) Nrequalc3|]}|VqdSrrr'rrZr r rk z1_ROComparison._generate_report..c3rrrrrZr r rk!rdeleterreplace) _c3_reportdifflibSequenceMatcherrur_legacy_report get_opcodesextend_ROComparison__moverrmaxrorr) r3rmatcher c3_report legacy_reportopcodeleg1leg2c31c32c3_chunk legacy_chunk chunk_sizer rZr _generate_reports.    z_ROComparison._generate_reportcCs:g}|jjr |d|jjr|d|rd|SdS)Ndirectrz+no)r4rsrlrnjoin)r3 inconsistentr r r _inconsistent_label2s   z!_ROComparison._inconsistent_labelc s|\}}t|t|ksJdd|D}dd|D}t|t|ks(Jdtdd|Dtdd|D}dt|jf}d t|j|jf}|||d t|g}|fd dt||D7}d |S) NcSg|]}t|qSr rrr r r rj?z)_ROComparison.__str__..cSrr rrr r r rj@rrcs|]}t|VqdSrrorr r r rkGz(_ROComparison.__str__..csrrrrr r r rkHrzLegacy RO (len=%s)zC3 RO (len=%s; inconsistent=%s)=cs&g|]\}}||qSr )ljust)r'leftrightmax_leftpaddingr r rjTs ) rrorrurrrzipr) r3rr left_lines right_lines max_right left_title right_titlerr rr r8;s(  z_ROComparison.__str__)r r"r#objectrrrrrrrrrr2rrrrr8r r r r rs "  rcCst|||}|}|dur|n|j}|dur|n|j}|s!|ru|j} t| ts+Jt|ts2J| |k} | rJdd| D} dd|D} | | k} | rZt||| } t d|| |j rq| |krqt||| } t d|| |j |ru| S|S)aR ro(C) -> list Compute the precedence list (mro) according to C3. :return: A fresh `list` object. .. versionchanged:: 5.0.0 Add the *strict*, *log_changed_ro* and *use_legacy_ro* keyword arguments. These are provisional and likely to be removed in the future. They are most useful for testing. NcSg|]}|tur|qSr _ROOTrr r r rj~rzro..cSrr rrr r r rjrz.Object %r has different legacy and C3 MROs: %szVObject %r had inconsistent IRO and used the legacy RO: %s Inconsistency entered at: %s) r]rgrXrrru isinstancerYrr rr\rs)r-rcrdlog_changed_ro use_legacy_rorgrX log_changed use_legacyruchangedlegacy_without_rootmro_without_root comparisonr r r r`s8  rcCst|ddj S)zn Check if the resolution order for *C*, as computed by :func:`ro`, is consistent according to C3. FN)r]rgr\)r-r r r is_consistentsr)NNNN)r$ __future__r __docformat____all__rr rrr PendingDeprecationWarningrr1rintr9rrCrUr]r_rarrrrr r r r s. E  O  5