Skip to content

Commit 2ba4b49

Browse files
committed
Update readme
1 parent 2a14bc7 commit 2ba4b49

File tree

1 file changed

+59
-14
lines changed

1 file changed

+59
-14
lines changed

README.rst

Lines changed: 59 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,22 +37,71 @@ Installation
3737
$ pip install immutables
3838

3939

40-
immutables.Map
41-
--------------
40+
API
41+
---
4242

43-
The ``Map`` object implements ``collections.abc.Mapping`` ABC
43+
``immutables.Map`` is an unordered immutable mapping. ``Map`` objects
44+
are hashable, comparable, and pickleable.
45+
46+
The ``Map`` object implements the ``collections.abc.Mapping`` ABC
4447
so working with it is very similar to working with Python dicts.
4548

46-
The only exception are its ``Map.set()`` and ``Map.delete()`` methods
47-
which return a new instance of ``Map``:
49+
import immutables
50+
51+
map = immutables.Map(a=1, b=2)
52+
53+
print(map['a'])
54+
# will print '1'
55+
56+
print(map.get('z', 100))
57+
# will print '100'
58+
59+
print('z' in map)
60+
# will print 'False'
61+
62+
Since Maps are immutable, there is a special API for mutations that
63+
allow apply changes to the Map object and create new (derived) Maps::
64+
65+
map2 = map.set('a', 10)
66+
print(map, map2)
67+
# will print:
68+
# <immutables.Map({'a': 1, 'b': 2})>
69+
# <immutables.Map({'a': 10, 'b': 2})>
4870

49-
.. code-block:: python
71+
map3 = map2.delete('b')
72+
print(map, map2, map3)
73+
# will print:
74+
# <immutables.Map({'a': 1, 'b': 2})>
75+
# <immutables.Map({'a': 10, 'b': 2})>
76+
# <immutables.Map({'a': 10})>
5077

51-
m1 = Map() # an empty Map
52-
m2 = m1.set('key1', 'val1') # m2 has a 'key1' key, m1 is still empty
78+
Maps also implement APIs for bulk updates: ``MapMutation`` objects::
5379

54-
m3 = m2.set('key2', 'val2')
55-
m3 = m3.delete('key1') # m3 has only a 'key2' key
80+
map_mutation = map.mutate()
81+
map_mutation['a'] = 100
82+
del map_mutation['b']
83+
map_mutation.set('y', 'y')
84+
85+
map2 = map_mutation.finalize()
86+
87+
print(map, map2)
88+
# will print:
89+
# <immutables.Map({'a': 1, 'b': 2})>
90+
# <immutables.Map({'a': 100, 'y': 'y'})>
91+
92+
``MapMutation`` objects are context managers. Here's the above example
93+
rewritten in a more idiomatic way::
94+
95+
with map.mutate() as mm:
96+
mm['a'] = 100
97+
del mm['b']
98+
mm.set('y', 'y')
99+
map2 = mm.finalize()
100+
101+
print(map, map2)
102+
# will print:
103+
# <immutables.Map({'a': 1, 'b': 2})>
104+
# <immutables.Map({'a': 100, 'y': 'y'})>
56105

57106

58107
Further development
@@ -61,10 +110,6 @@ Further development
61110
* An immutable version of Python ``set`` type with efficient
62111
``add()`` and ``discard()`` operations.
63112

64-
* Add support for efficient ``Map.update()`` operation, allow to
65-
pass a set of key/values to ``Map()``, and add support for
66-
pickling.
67-
68113

69114
License
70115
-------

0 commit comments

Comments
 (0)