| |
| |
| |
| |
| |
|
|
|
|
| |
| |
| |
| |
| |
|
|
|
|
| """Provide :class:`BidictBase`.""" |
|
|
| from __future__ import annotations |
|
|
| import typing as t |
| import weakref |
| from itertools import starmap |
| from operator import eq |
| from types import MappingProxyType |
|
|
| from ._abc import BidirectionalMapping |
| from ._dup import DROP_NEW |
| from ._dup import DROP_OLD |
| from ._dup import ON_DUP_DEFAULT |
| from ._dup import RAISE |
| from ._dup import OnDup |
| from ._exc import DuplicationError |
| from ._exc import KeyAndValueDuplicationError |
| from ._exc import KeyDuplicationError |
| from ._exc import ValueDuplicationError |
| from ._iter import inverted |
| from ._iter import iteritems |
| from ._typing import KT |
| from ._typing import MISSING |
| from ._typing import OKT |
| from ._typing import OVT |
| from ._typing import VT |
| from ._typing import Maplike |
| from ._typing import MapOrItems |
|
|
|
|
| OldKV = t.Tuple[OKT[KT], OVT[VT]] |
| DedupResult = t.Optional[OldKV[KT, VT]] |
| Unwrites = t.List[t.Tuple[t.Any, ...]] |
| BT = t.TypeVar('BT', bound='BidictBase[t.Any, t.Any]') |
|
|
|
|
| class BidictKeysView(t.KeysView[KT], t.ValuesView[KT]): |
| """Since the keys of a bidict are the values of its inverse (and vice versa), |
| the :class:`~collections.abc.ValuesView` result of calling *bi.values()* |
| is also a :class:`~collections.abc.KeysView` of *bi.inverse*. |
| """ |
|
|
|
|
| class BidictBase(BidirectionalMapping[KT, VT]): |
| """Base class implementing :class:`BidirectionalMapping`.""" |
|
|
| |
| |
| |
| |
| |
| |
| |
| on_dup = ON_DUP_DEFAULT |
|
|
| _fwdm: t.MutableMapping[KT, VT] |
| _invm: t.MutableMapping[VT, KT] |
|
|
| |
| _fwdm_cls: t.ClassVar[type[t.MutableMapping[t.Any, t.Any]]] = dict |
| _invm_cls: t.ClassVar[type[t.MutableMapping[t.Any, t.Any]]] = dict |
|
|
| |
| _inv_cls: t.ClassVar[type[BidictBase[t.Any, t.Any]]] |
|
|
| def __init_subclass__(cls) -> None: |
| super().__init_subclass__() |
| cls._init_class() |
|
|
| @classmethod |
| def _init_class(cls) -> None: |
| cls._ensure_inv_cls() |
| cls._set_reversed() |
|
|
| __reversed__: t.ClassVar[t.Any] |
|
|
| @classmethod |
| def _set_reversed(cls) -> None: |
| """Set __reversed__ for subclasses that do not set it explicitly |
| according to whether backing mappings are reversible. |
| """ |
| if cls is not BidictBase: |
| resolved = cls.__reversed__ |
| overridden = resolved is not BidictBase.__reversed__ |
| if overridden: |
| return |
| backing_reversible = all(issubclass(i, t.Reversible) for i in (cls._fwdm_cls, cls._invm_cls)) |
| cls.__reversed__ = _fwdm_reversed if backing_reversible else None |
|
|
| @classmethod |
| def _ensure_inv_cls(cls) -> None: |
| """Ensure :attr:`_inv_cls` is set, computing it dynamically if necessary. |
| |
| All subclasses provided in :mod:`bidict` are their own inverse classes, |
| i.e., their backing forward and inverse mappings are both the same type, |
| but users may define subclasses where this is not the case. |
| This method ensures that the inverse class is computed correctly regardless. |
| |
| See: :ref:`extending:Dynamic Inverse Class Generation` |
| (https://bidict.rtfd.io/extending.html#dynamic-inverse-class-generation) |
| """ |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if getattr(cls, '__dict__', {}).get('_inv_cls'): |
| return |
| cls._inv_cls = cls._make_inv_cls() |
|
|
| @classmethod |
| def _make_inv_cls(cls: type[BT]) -> type[BT]: |
| diff = cls._inv_cls_dict_diff() |
| cls_is_own_inv = all(getattr(cls, k, MISSING) == v for (k, v) in diff.items()) |
| if cls_is_own_inv: |
| return cls |
| |
| |
| diff['_inv_cls'] = cls |
| inv_cls = type(f'{cls.__name__}Inv', (cls, GeneratedBidictInverse), diff) |
| inv_cls.__module__ = cls.__module__ |
| return t.cast(t.Type[BT], inv_cls) |
|
|
| @classmethod |
| def _inv_cls_dict_diff(cls) -> dict[str, t.Any]: |
| return { |
| '_fwdm_cls': cls._invm_cls, |
| '_invm_cls': cls._fwdm_cls, |
| } |
|
|
| def __init__(self, arg: MapOrItems[KT, VT] = (), /, **kw: VT) -> None: |
| """Make a new bidirectional mapping. |
| The signature behaves like that of :class:`dict`. |
| ktems passed via positional arg are processed first, |
| followed by any items passed via keyword argument. |
| Any duplication encountered along the way |
| is handled as per :attr:`on_dup`. |
| """ |
| self._fwdm = self._fwdm_cls() |
| self._invm = self._invm_cls() |
| self._update(arg, kw, rollback=False) |
|
|
| |
| |
| |
| @property |
| def inverse(self) -> BidictBase[VT, KT]: |
| """The inverse of this bidirectional mapping instance.""" |
| |
| |
| |
| |
| |
| |
|
|
| |
| inv: BidictBase[VT, KT] | None = getattr(self, '_inv', None) |
| if inv is not None: |
| return inv |
| |
| invweak = getattr(self, '_invweak', None) |
| if invweak is not None: |
| inv = invweak() |
| if inv is not None: |
| return inv |
| |
| inv = self._make_inverse() |
| self._inv: BidictBase[VT, KT] | None = inv |
| self._invweak: weakref.ReferenceType[BidictBase[VT, KT]] | None = None |
| |
| |
| inv._inv = None |
| inv._invweak = weakref.ref(self) |
| |
| |
| |
| return inv |
|
|
| def _make_inverse(self) -> BidictBase[VT, KT]: |
| inv: BidictBase[VT, KT] = self._inv_cls() |
| inv._fwdm = self._invm |
| inv._invm = self._fwdm |
| return inv |
|
|
| @property |
| def inv(self) -> BidictBase[VT, KT]: |
| """Alias for :attr:`inverse`.""" |
| return self.inverse |
|
|
| def __repr__(self) -> str: |
| """See :func:`repr`.""" |
| clsname = self.__class__.__name__ |
| items = dict(self.items()) if self else '' |
| return f'{clsname}({items})' |
|
|
| def values(self) -> BidictKeysView[VT]: |
| """A set-like object providing a view on the contained values. |
| |
| Since the values of a bidict are equivalent to the keys of its inverse, |
| this method returns a set-like object for this bidict's values |
| rather than just a collections.abc.ValuesView. |
| This object supports set operations like union and difference, |
| and constant- rather than linear-time containment checks, |
| and is no more expensive to provide than the less capable |
| collections.abc.ValuesView would be. |
| |
| See :meth:`keys` for more information. |
| """ |
| return t.cast(BidictKeysView[VT], self.inverse.keys()) |
|
|
| def keys(self) -> t.KeysView[KT]: |
| """A set-like object providing a view on the contained keys. |
| |
| When *b._fwdm* is a :class:`dict`, *b.keys()* returns a |
| *dict_keys* object that behaves exactly the same as |
| *collections.abc.KeysView(b)*, except for |
| |
| - offering better performance |
| |
| - being reversible on Python 3.8+ |
| |
| - having a .mapping attribute in Python 3.10+ |
| that exposes a mappingproxy to *b._fwdm*. |
| """ |
| fwdm, fwdm_cls = self._fwdm, self._fwdm_cls |
| return fwdm.keys() if fwdm_cls is dict else BidictKeysView(self) |
|
|
| def items(self) -> t.ItemsView[KT, VT]: |
| """A set-like object providing a view on the contained items. |
| |
| When *b._fwdm* is a :class:`dict`, *b.items()* returns a |
| *dict_items* object that behaves exactly the same as |
| *collections.abc.ItemsView(b)*, except for: |
| |
| - offering better performance |
| |
| - being reversible on Python 3.8+ |
| |
| - having a .mapping attribute in Python 3.10+ |
| that exposes a mappingproxy to *b._fwdm*. |
| """ |
| return self._fwdm.items() if self._fwdm_cls is dict else super().items() |
|
|
| |
| |
| |
| def __contains__(self, key: t.Any) -> bool: |
| """True if the mapping contains the specified key, else False.""" |
| return key in self._fwdm |
|
|
| |
| |
| |
| def __eq__(self, other: object) -> bool: |
| """*x.__eq__(other) ⟺ x == other* |
| |
| Equivalent to *dict(x.items()) == dict(other.items())* |
| but more efficient. |
| |
| Note that :meth:`bidict's __eq__() <bidict.BidictBase.__eq__>` implementation |
| is inherited by subclasses, |
| in particular by the ordered bidict subclasses, |
| so even with ordered bidicts, |
| :ref:`== comparison is order-insensitive <eq-order-insensitive>` |
| (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive). |
| |
| *See also* :meth:`equals_order_sensitive` |
| """ |
| if isinstance(other, t.Mapping): |
| return self._fwdm.items() == other.items() |
| |
| return NotImplemented |
|
|
| def equals_order_sensitive(self, other: object) -> bool: |
| """Order-sensitive equality check. |
| |
| *See also* :ref:`eq-order-insensitive` |
| (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive) |
| """ |
| if not isinstance(other, t.Mapping) or len(self) != len(other): |
| return False |
| return all(starmap(eq, zip(self.items(), other.items()))) |
|
|
| def _dedup(self, key: KT, val: VT, on_dup: OnDup) -> DedupResult[KT, VT]: |
| """Check *key* and *val* for any duplication in self. |
| |
| Handle any duplication as per the passed in *on_dup*. |
| |
| If (key, val) is already present, return None |
| since writing (key, val) would be a no-op. |
| |
| If duplication is found and the corresponding :class:`~bidict.OnDupAction` is |
| :attr:`~bidict.DROP_NEW`, return None. |
| |
| If duplication is found and the corresponding :class:`~bidict.OnDupAction` is |
| :attr:`~bidict.RAISE`, raise the appropriate exception. |
| |
| If duplication is found and the corresponding :class:`~bidict.OnDupAction` is |
| :attr:`~bidict.DROP_OLD`, or if no duplication is found, |
| return *(oldkey, oldval)*. |
| """ |
| fwdm, invm = self._fwdm, self._invm |
| oldval: OVT[VT] = fwdm.get(key, MISSING) |
| oldkey: OKT[KT] = invm.get(val, MISSING) |
| isdupkey, isdupval = oldval is not MISSING, oldkey is not MISSING |
| if isdupkey and isdupval: |
| if key == oldkey: |
| assert val == oldval |
| |
| return None |
| |
| if on_dup.val is RAISE: |
| raise KeyAndValueDuplicationError(key, val) |
| if on_dup.val is DROP_NEW: |
| return None |
| assert on_dup.val is DROP_OLD |
| |
| elif isdupkey: |
| if on_dup.key is RAISE: |
| raise KeyDuplicationError(key) |
| if on_dup.key is DROP_NEW: |
| return None |
| assert on_dup.key is DROP_OLD |
| |
| elif isdupval: |
| if on_dup.val is RAISE: |
| raise ValueDuplicationError(val) |
| if on_dup.val is DROP_NEW: |
| return None |
| assert on_dup.val is DROP_OLD |
| |
| |
| return oldkey, oldval |
|
|
| def _write(self, newkey: KT, newval: VT, oldkey: OKT[KT], oldval: OVT[VT], unwrites: Unwrites | None) -> None: |
| """Insert (newkey, newval), extending *unwrites* with associated inverse operations if provided. |
| |
| *oldkey* and *oldval* are as returned by :meth:`_dedup`. |
| |
| If *unwrites* is not None, it is extended with the inverse operations necessary to undo the write. |
| This design allows :meth:`_update` to roll back a partially applied update that fails part-way through |
| when necessary. |
| |
| This design also allows subclasses that require additional operations to easily extend this implementation. |
| For example, :class:`bidict.OrderedBidictBase` calls this inherited implementation, and then extends *unwrites* |
| with additional operations needed to keep its internal linked list nodes consistent with its items' order |
| as changes are made. |
| """ |
| fwdm, invm = self._fwdm, self._invm |
| fwdm_set, invm_set = fwdm.__setitem__, invm.__setitem__ |
| fwdm_del, invm_del = fwdm.__delitem__, invm.__delitem__ |
| |
| fwdm_set(newkey, newval) |
| invm_set(newval, newkey) |
| if oldval is MISSING and oldkey is MISSING: |
| |
| if unwrites is not None: |
| unwrites.extend(( |
| (fwdm_del, newkey), |
| (invm_del, newval), |
| )) |
| elif oldval is not MISSING and oldkey is not MISSING: |
| |
| fwdm_del(oldkey) |
| invm_del(oldval) |
| if unwrites is not None: |
| unwrites.extend(( |
| (fwdm_set, newkey, oldval), |
| (invm_set, oldval, newkey), |
| (fwdm_set, oldkey, newval), |
| (invm_set, newval, oldkey), |
| )) |
| elif oldval is not MISSING: |
| |
| invm_del(oldval) |
| if unwrites is not None: |
| unwrites.extend(( |
| (fwdm_set, newkey, oldval), |
| (invm_set, oldval, newkey), |
| (invm_del, newval), |
| )) |
| else: |
| assert oldkey is not MISSING |
| |
| fwdm_del(oldkey) |
| if unwrites is not None: |
| unwrites.extend(( |
| (fwdm_set, oldkey, newval), |
| (invm_set, newval, oldkey), |
| (fwdm_del, newkey), |
| )) |
|
|
| def _update( |
| self, |
| arg: MapOrItems[KT, VT], |
| kw: t.Mapping[str, VT] = MappingProxyType({}), |
| *, |
| rollback: bool | None = None, |
| on_dup: OnDup | None = None, |
| ) -> None: |
| """Update with the items from *arg* and *kw*, maybe failing and rolling back as per *on_dup* and *rollback*.""" |
| |
| if not isinstance(arg, (t.Iterable, Maplike)): |
| raise TypeError(f"'{arg.__class__.__name__}' object is not iterable") |
| if not arg and not kw: |
| return |
| if on_dup is None: |
| on_dup = self.on_dup |
| if rollback is None: |
| rollback = RAISE in on_dup |
|
|
| |
| if not self and not kw and isinstance(arg, BidictBase): |
| self._init_from(arg) |
| return |
|
|
| |
| |
| if rollback and isinstance(arg, t.Sized) and len(arg) + len(kw) > len(self): |
| tmp = self.copy() |
| tmp._update(arg, kw, rollback=False, on_dup=on_dup) |
| self._init_from(tmp) |
| return |
|
|
| |
| |
| |
| |
| |
| write = self._write |
| unwrites: Unwrites | None = [] if rollback else None |
| for key, val in iteritems(arg, **kw): |
| try: |
| dedup_result = self._dedup(key, val, on_dup) |
| except DuplicationError: |
| if unwrites is not None: |
| for fn, *args in reversed(unwrites): |
| fn(*args) |
| raise |
| if dedup_result is not None: |
| write(key, val, *dedup_result, unwrites=unwrites) |
|
|
| def __copy__(self: BT) -> BT: |
| """Used for the copy protocol. See the :mod:`copy` module.""" |
| return self.copy() |
|
|
| def copy(self: BT) -> BT: |
| """Make a (shallow) copy of this bidict.""" |
| |
| |
| |
| |
| return self._from_other(self.__class__, self) |
|
|
| @staticmethod |
| def _from_other(bt: type[BT], other: MapOrItems[KT, VT], inv: bool = False) -> BT: |
| """Fast, private constructor based on :meth:`_init_from`. |
| |
| If *inv* is true, return the inverse of the instance instead of the instance itself. |
| (Useful for pickling with dynamically-generated inverse classes -- see :meth:`__reduce__`.) |
| """ |
| inst = bt() |
| inst._init_from(other) |
| return t.cast(BT, inst.inverse) if inv else inst |
|
|
| def _init_from(self, other: MapOrItems[KT, VT]) -> None: |
| """Fast init from *other*, bypassing item-by-item duplication checking.""" |
| self._fwdm.clear() |
| self._invm.clear() |
| self._fwdm.update(other) |
| |
| |
| inv = other.inverse if isinstance(other, BidictBase) else inverted(self._fwdm) |
| self._invm.update(inv) |
|
|
| |
| |
| def __or__(self: BT, other: t.Mapping[KT, VT]) -> BT: |
| """Return self|other.""" |
| if not isinstance(other, t.Mapping): |
| return NotImplemented |
| new = self.copy() |
| new._update(other, rollback=False) |
| return new |
|
|
| def __ror__(self: BT, other: t.Mapping[KT, VT]) -> BT: |
| """Return other|self.""" |
| if not isinstance(other, t.Mapping): |
| return NotImplemented |
| new = self.__class__(other) |
| new._update(self, rollback=False) |
| return new |
|
|
| def __len__(self) -> int: |
| """The number of contained items.""" |
| return len(self._fwdm) |
|
|
| def __iter__(self) -> t.Iterator[KT]: |
| """Iterator over the contained keys.""" |
| return iter(self._fwdm) |
|
|
| def __getitem__(self, key: KT) -> VT: |
| """*x.__getitem__(key) ⟺ x[key]*""" |
| return self._fwdm[key] |
|
|
| def __reduce__(self) -> tuple[t.Any, ...]: |
| """Return state information for pickling.""" |
| cls = self.__class__ |
| inst: t.Mapping[t.Any, t.Any] = self |
| |
| |
| |
| if should_invert := isinstance(self, GeneratedBidictInverse): |
| cls = self._inv_cls |
| inst = self.inverse |
| return self._from_other, (cls, dict(inst), should_invert) |
|
|
|
|
| |
| def _fwdm_reversed(self: BidictBase[KT, t.Any]) -> t.Iterator[KT]: |
| """Iterator over the contained keys in reverse order.""" |
| assert isinstance(self._fwdm, t.Reversible) |
| return reversed(self._fwdm) |
|
|
|
|
| BidictBase._init_class() |
|
|
|
|
| class GeneratedBidictInverse: |
| """Base class for dynamically-generated inverse bidict classes.""" |
|
|
|
|
| |
| |
| |
| |
|
|