codekingpro/portable-devtools
114k
1# Copyright 2009-2024 Joshua Bronson. All rights reserved.2#3# This Source Code Form is subject to the terms of the Mozilla Public4# License, v. 2.0. If a copy of the MPL was not distributed with this5# file, You can obtain one at http://mozilla.org/MPL/2.0/.6 7 8# * Code review nav *9# (see comments in __init__.py)10# ============================================================================11# ← Prev: __init__.py Current: _abc.py Next: _base.py →12# ============================================================================13 14 15"""Provide the :class:`BidirectionalMapping` abstract base class."""16 17from __future__ import annotations18 19import typing as t20from abc import abstractmethod21 22from ._typing import KT23from ._typing import VT24 25 26class BidirectionalMapping(t.Mapping[KT, VT]):27 """Abstract base class for bidirectional mapping types.28 29 Extends :class:`collections.abc.Mapping` primarily by adding the30 (abstract) :attr:`inverse` property,31 which implementers of :class:`BidirectionalMapping`32 should override to return a reference to the inverse33 :class:`BidirectionalMapping` instance.34 """35 36 __slots__ = ()37 38 @property39 @abstractmethod40 def inverse(self) -> BidirectionalMapping[VT, KT]:41 """The inverse of this bidirectional mapping instance.42 43 *See also* :attr:`bidict.BidictBase.inverse`, :attr:`bidict.BidictBase.inv`44 45 :raises NotImplementedError: Meant to be overridden in subclasses.46 """47 # The @abstractmethod decorator prevents subclasses from being instantiated unless they48 # override this method. But an overriding implementation may merely return super().inverse,49 # in which case this implementation is used. Raise NotImplementedError to indicate that50 # subclasses must actually provide their own implementation.51 raise NotImplementedError52 53 def __inverted__(self) -> t.Iterator[tuple[VT, KT]]:54 """Get an iterator over the items in :attr:`inverse`.55 56 This is functionally equivalent to iterating over the items in the57 forward mapping and inverting each one on the fly, but this provides a58 more efficient implementation: Assuming the already-inverted items59 are stored in :attr:`inverse`, just return an iterator over them directly.60 61 Providing this default implementation enables external functions,62 particularly :func:`~bidict.inverted`, to use this optimized63 implementation when available, instead of having to invert on the fly.64 65 *See also* :func:`bidict.inverted`66 """67 return iter(self.inverse.items())68 69 70class MutableBidirectionalMapping(BidirectionalMapping[KT, VT], t.MutableMapping[KT, VT]):71 """Abstract base class for mutable bidirectional mapping types."""72 73 __slots__ = ()74 75 76# * Code review nav *77# ============================================================================78# ← Prev: __init__.py Current: _abc.py Next: _base.py →79# ============================================================================80 