| 1 |
Extending ``bidict`` |
| 2 |
-------------------- |
| 3 |
|
| 4 |
Bidict was written with extensibility in mind. |
| 5 |
|
| 6 |
Let's look at some examples. |
| 7 |
|
| 8 |
|
| 9 |
``YoloBidict`` Recipe |
| 10 |
##################### |
| 11 |
|
| 12 |
If you'd like |
| 13 |
:attr:`~bidict.ON_DUP_DROP_OLD` |
| 14 |
to be the default :class:`~bidict.BidictBase.on_dup` behavior |
| 15 |
(for :meth:`~bidict.BidictBase.__init__`, |
| 16 |
:meth:`~bidict.MutableBidict.__setitem__`, and |
| 17 |
:meth:`~bidict.MutableBidict.update`), |
| 18 |
you can use the following recipe: |
| 19 |
|
| 20 |
.. doctest:: |
| 21 |
|
| 22 |
>>> from bidict import bidict, ON_DUP_DROP_OLD |
| 23 |
|
| 24 |
>>> class YoloBidict(bidict): |
| 25 |
... on_dup = ON_DUP_DROP_OLD |
| 26 |
|
| 27 |
>>> b = YoloBidict({'one': 1}) |
| 28 |
>>> b['two'] = 1 # succeeds, no ValueDuplicationError |
| 29 |
>>> b |
| 30 |
YoloBidict({'two': 1}) |
| 31 |
|
| 32 |
>>> b.update({'three': 1}) # ditto |
| 33 |
>>> b |
| 34 |
YoloBidict({'three': 1}) |
| 35 |
|
| 36 |
Of course, ``YoloBidict``'s inherited |
| 37 |
:meth:`~bidict.MutableBidict.put` and |
| 38 |
:meth:`~bidict.MutableBidict.putall` methods |
| 39 |
still allow specifying a custom :class:`~bidict.OnDup` |
| 40 |
per call via the *on_dup* argument, |
| 41 |
and will both still default to raising for all duplication types. |
| 42 |
|
| 43 |
Further demonstrating :mod:`bidict`'s extensibility, |
| 44 |
to make an ``OrderedYoloBidict``, |
| 45 |
the class above can simply inherit from |
| 46 |
:class:`bidict.OrderedBidict` |
| 47 |
rather than :class:`bidict.bidict`. |
| 48 |
|
| 49 |
|
| 50 |
Beware of ``ON_DUP_DROP_OLD`` |
| 51 |
::::::::::::::::::::::::::::: |
| 52 |
|
| 53 |
There's a good reason that :mod:`bidict` does not provide a ``YoloBidict`` out of the box. |
| 54 |
|
| 55 |
Before you decide to use a ``YoloBidict`` in your own code, |
| 56 |
beware of the following potentially unexpected, dangerous behavior: |
| 57 |
|
| 58 |
.. doctest:: |
| 59 |
|
| 60 |
>>> b = YoloBidict({'one': 1, 'two': 2}) # b contains two items |
| 61 |
>>> b['one'] = 2 # update one of the items |
| 62 |
>>> b # now b only has one item! |
| 63 |
YoloBidict({'one': 2}) |
| 64 |
|
| 65 |
As covered in :ref:`basic-usage:collapsing overwrites`, |
| 66 |
setting an existing key to the value of a different existing item |
| 67 |
causes both existing items to quietly collapse into a single new item. |
| 68 |
|
| 69 |
The opposite customization would look something like: |
| 70 |
|
| 71 |
.. doctest:: |
| 72 |
|
| 73 |
>>> from bidict import ON_DUP_RAISE |
| 74 |
|
| 75 |
>>> class YodoBidict(bidict): # yodo: you only die once! |
| 76 |
... on_dup = ON_DUP_RAISE |
| 77 |
|
| 78 |
>>> b = YodoBidict({'one': 1}) |
| 79 |
>>> b['one'] = 2 # Unlike a regular bidict, YodoBidict won't allow this. |
| 80 |
Traceback (most recent call last): |
| 81 |
... |
| 82 |
bidict.KeyDuplicationError: one |
| 83 |
>>> b |
| 84 |
YodoBidict({'one': 1}) |
| 85 |
>>> b.forceput('one', 2) # Any type of overwrite requires more force. |
| 86 |
>>> b |
| 87 |
YodoBidict({'one': 2}) |
| 88 |
|
| 89 |
|
| 90 |
``WeakrefBidict`` Recipe |
| 91 |
######################## |
| 92 |
|
| 93 |
Suppose you need to store some objects in a bidict |
| 94 |
without incrementing their refcounts. |
| 95 |
|
| 96 |
With :class:`~bidict.BidictBase`\'s |
| 97 |
:attr:`~bidict.BidictBase._fwdm_cls` (forward mapping class) and |
| 98 |
:attr:`~bidict.BidictBase._invm_cls` (inverse mapping class) attributes, |
| 99 |
accomplishing this is as simple as: |
| 100 |
|
| 101 |
.. doctest:: |
| 102 |
|
| 103 |
>>> from bidict import MutableBidict |
| 104 |
>>> from weakref import WeakKeyDictionary, WeakValueDictionary |
| 105 |
|
| 106 |
>>> class WeakrefBidict(MutableBidict): |
| 107 |
... _fwdm_cls = WeakKeyDictionary |
| 108 |
... _invm_cls = WeakValueDictionary |
| 109 |
|
| 110 |
Now you can insert items into *WeakrefBidict* without incrementing their refcounts: |
| 111 |
|
| 112 |
.. doctest:: |
| 113 |
|
| 114 |
>>> b = WeakrefBidict() |
| 115 |
>>> o1, o2 = frozenset({1}), frozenset({2}) |
| 116 |
>>> b[o1] = o2 |
| 117 |
|
| 118 |
Since o1 and o2 are the only strong references to these objects, |
| 119 |
if you delete these references, the refcounts will go to zero |
| 120 |
and the objects will immediately be deallocated on CPython, |
| 121 |
since the *WeakrefBidict* isn't holding on to them: |
| 122 |
|
| 123 |
.. use `:skipif: pypy` for the test below once https://github.com/thisch/pytest-sphinx/issues/9 is fixed |
| 124 |
|
| 125 |
.. doctest:: |
| 126 |
|
| 127 |
>>> del o1, o2 # after this, b immediately becomes empty on CPython: |
| 128 |
>>> if sys.implementation.name == 'cpython': |
| 129 |
... assert not b |
| 130 |
|
| 131 |
|
| 132 |
``SortedBidict`` Recipes |
| 133 |
######################## |
| 134 |
|
| 135 |
Suppose you need a bidict that maintains its items in sorted order. |
| 136 |
The Python standard library does not include any sorted dict types, |
| 137 |
but the excellent |
| 138 |
`sortedcontainers <http://www.grantjenks.com/docs/sortedcontainers/>`__ and |
| 139 |
`sortedcollections <http://www.grantjenks.com/docs/sortedcollections/>`__ |
| 140 |
libraries do. |
| 141 |
|
| 142 |
Using these, along with :class:`~bidict.BidictBase`'s |
| 143 |
:attr:`~bidict.BidictBase._fwdm_cls` (forward mapping class) and |
| 144 |
:attr:`~bidict.BidictBase._invm_cls` (inverse mapping class) attributes, |
| 145 |
creating a sorted bidict is simple: |
| 146 |
|
| 147 |
.. doctest:: |
| 148 |
|
| 149 |
>>> from sortedcontainers import SortedDict |
| 150 |
|
| 151 |
>>> class SortedBidict(MutableBidict): |
| 152 |
... """A sorted bidict whose forward items stay sorted by their keys, |
| 153 |
... and whose inverse items stay sorted by *their* keys. |
| 154 |
... Note: As a result, an instance and its inverse yield their items |
| 155 |
... in different orders. |
| 156 |
... """ |
| 157 |
... _fwdm_cls = SortedDict |
| 158 |
... _invm_cls = SortedDict |
| 159 |
|
| 160 |
>>> b = SortedBidict({'Tokyo': 'Japan', 'Cairo': 'Egypt'}) |
| 161 |
>>> b |
| 162 |
SortedBidict({'Cairo': 'Egypt', 'Tokyo': 'Japan'}) |
| 163 |
|
| 164 |
>>> b['Lima'] = 'Peru' |
| 165 |
|
| 166 |
>>> list(b.items()) # stays sorted by key |
| 167 |
[('Cairo', 'Egypt'), ('Lima', 'Peru'), ('Tokyo', 'Japan')] |
| 168 |
|
| 169 |
>>> list(b.inverse.items()) # .inverse stays sorted by *its* keys (b's values) |
| 170 |
[('Egypt', 'Cairo'), ('Japan', 'Tokyo'), ('Peru', 'Lima')] |
| 171 |
|
| 172 |
|
| 173 |
Here's a recipe for a sorted bidict whose forward items stay sorted by their keys, |
| 174 |
and whose inverse items stay sorted by their values. i.e. An instance and its inverse |
| 175 |
will yield their items in *the same* order: |
| 176 |
|
| 177 |
.. doctest:: |
| 178 |
|
| 179 |
>>> from sortedcollections import ValueSortedDict |
| 180 |
|
| 181 |
>>> class KeySortedBidict(MutableBidict): |
| 182 |
... _fwdm_cls = SortedDict |
| 183 |
... _invm_cls = ValueSortedDict |
| 184 |
|
| 185 |
>>> elem_by_atomicnum = KeySortedBidict({ |
| 186 |
... 6: 'carbon', 1: 'hydrogen', 2: 'helium'}) |
| 187 |
|
| 188 |
>>> list(elem_by_atomicnum.items()) # stays sorted by key |
| 189 |
[(1, 'hydrogen'), (2, 'helium'), (6, 'carbon')] |
| 190 |
|
| 191 |
>>> list(elem_by_atomicnum.inverse.items()) # .inverse stays sorted by value |
| 192 |
[('hydrogen', 1), ('helium', 2), ('carbon', 6)] |
| 193 |
|
| 194 |
>>> elem_by_atomicnum[4] = 'beryllium' |
| 195 |
|
| 196 |
>>> list(elem_by_atomicnum.inverse.items()) |
| 197 |
[('hydrogen', 1), ('helium', 2), ('beryllium', 4), ('carbon', 6)] |
| 198 |
|
| 199 |
|
| 200 |
Automatic "Get Attribute" Pass-Through |
| 201 |
###################################### |
| 202 |
|
| 203 |
Python makes it easy to customize a class's "get attribute" behavior. |
| 204 |
You can take advantage of this to pass attribute access |
| 205 |
through to the backing ``_fwdm`` mapping |
| 206 |
when an attribute is not provided by the bidict class itself: |
| 207 |
|
| 208 |
>>> def __getattribute__(self, name): |
| 209 |
... try: |
| 210 |
... return object.__getattribute__(self, name) |
| 211 |
... except AttributeError: |
| 212 |
... return getattr(self._fwdm, name) |
| 213 |
|
| 214 |
>>> KeySortedBidict.__getattribute__ = __getattribute__ |
| 215 |
|
| 216 |
Now, even though this ``KeySortedBidict`` itself provides no ``peekitem`` attribute, |
| 217 |
you can still call ``peekitem`` on it |
| 218 |
and it will return the result of calling ``peekitem`` |
| 219 |
on the backing ``SortedDict``: |
| 220 |
|
| 221 |
>>> elem_by_atomicnum.peekitem() |
| 222 |
(6, 'carbon') |
| 223 |
|
| 224 |
|
| 225 |
Dynamic Inverse Class Generation |
| 226 |
################################ |
| 227 |
|
| 228 |
When a bidict class's |
| 229 |
:attr:`~bidict.BidictBase._fwdm_cls` and |
| 230 |
:attr:`~bidict.BidictBase._invm_cls` |
| 231 |
are the same, |
| 232 |
the bidict class is its own inverse class. |
| 233 |
(This is the case for all the |
| 234 |
:ref:`bidict classes <other-bidict-types:Bidict Types Diagram>` |
| 235 |
that come with :mod:`bidict`.) |
| 236 |
|
| 237 |
However, when a bidict's |
| 238 |
:attr:`~bidict.BidictBase._fwdm_cls` and |
| 239 |
:attr:`~bidict.BidictBase._invm_cls` differ, |
| 240 |
as in the ``KeySortedBidict`` and ``WeakrefBidict`` recipes above, |
| 241 |
the inverse class of the bidict |
| 242 |
needs to have its |
| 243 |
:attr:`~bidict.BidictBase._fwdm_cls` and |
| 244 |
:attr:`~bidict.BidictBase._invm_cls` swapped. |
| 245 |
|
| 246 |
:class:`~bidict.BidictBase` detects this |
| 247 |
and dynamically computes the correct inverse class for you automatically. |
| 248 |
|
| 249 |
You can see this if you inspect ``KeySortedBidict``'s inverse bidict: |
| 250 |
|
| 251 |
>>> elem_by_atomicnum.inverse.__class__.__name__ |
| 252 |
'KeySortedBidictInv' |
| 253 |
|
| 254 |
Notice that :class:`~bidict.BidictBase` automatically created a |
| 255 |
``KeySortedBidictInv`` class and used it for the inverse bidict. |
| 256 |
|
| 257 |
As expected, ``KeySortedBidictInv``'s |
| 258 |
:attr:`~bidict.BidictBase._fwdm_cls` and |
| 259 |
:attr:`~bidict.BidictBase._invm_cls` |
| 260 |
are the opposite of ``KeySortedBidict``'s: |
| 261 |
|
| 262 |
>>> elem_by_atomicnum.inverse._fwdm_cls.__name__ |
| 263 |
'ValueSortedDict' |
| 264 |
>>> elem_by_atomicnum.inverse._invm_cls.__name__ |
| 265 |
'SortedDict' |
| 266 |
|
| 267 |
:class:`~bidict.BidictBase` also ensures that round trips work as expected: |
| 268 |
|
| 269 |
>>> KeySortedBidictInv = elem_by_atomicnum.inverse.__class__ # i.e. a value-sorted bidict |
| 270 |
>>> atomicnum_by_elem = KeySortedBidictInv(elem_by_atomicnum.inverse) |
| 271 |
>>> atomicnum_by_elem |
| 272 |
KeySortedBidictInv({'hydrogen': 1, 'helium': 2, 'beryllium': 4, 'carbon': 6}) |
| 273 |
>>> KeySortedBidict(atomicnum_by_elem.inverse) == elem_by_atomicnum |
| 274 |
True |
| 275 |
|
| 276 |
|
| 277 |
----- |
| 278 |
|
| 279 |
This all goes to show how simple it can be |
| 280 |
to compose your own bidirectional mapping types |
| 281 |
out of the building blocks that :mod:`bidict` provides. |