README.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. Pyrsistent
  2. ==========
  3. .. image:: https://github.com/tobgu/pyrsistent/actions/workflows/tests.yaml/badge.svg
  4. :target: https://github.com/tobgu/pyrsistent/actions/workflows/tests.yaml
  5. .. _Pyrthon: https://www.github.com/tobgu/pyrthon
  6. .. _Pyrsistent_extras: https://github.com/mingmingrr/pyrsistent-extras
  7. Pyrsistent is a number of persistent collections (by some referred to as functional data structures). Persistent in
  8. the sense that they are immutable.
  9. All methods on a data structure that would normally mutate it instead return a new copy of the structure containing the
  10. requested updates. The original structure is left untouched.
  11. This will simplify the reasoning about what a program does since no hidden side effects ever can take place to these
  12. data structures. You can rest assured that the object you hold a reference to will remain the same throughout its
  13. lifetime and need not worry that somewhere five stack levels below you in the darkest corner of your application
  14. someone has decided to remove that element that you expected to be there.
  15. Pyrsistent is influenced by persistent data structures such as those found in the standard library of Clojure. The
  16. data structures are designed to share common elements through path copying.
  17. It aims at taking these concepts and make them as pythonic as possible so that they can be easily integrated into any python
  18. program without hassle.
  19. If you want use literal syntax to define them in your code rather
  20. than function calls check out Pyrthon_. Be aware, that one is experimental, unmaintained and alpha software.
  21. If you cannot find the persistent data structure you're looking for here you may want to take a look at
  22. Pyrsistent_extras_ which is maintained by @mingmingrr. If you still don't find what you're looking for please
  23. open an issue for discussion. If we agree that functionality is missing you may want to go ahead and create
  24. a Pull Request implement the missing functionality.
  25. Examples
  26. --------
  27. .. _Sequence: collections_
  28. .. _Hashable: collections_
  29. .. _Mapping: collections_
  30. .. _Mappings: collections_
  31. .. _Set: collections_
  32. .. _collections: https://docs.python.org/3/library/collections.abc.html
  33. .. _documentation: http://pyrsistent.readthedocs.org/
  34. The collection types and key features currently implemented are:
  35. * PVector_, similar to a python list
  36. * PMap_, similar to dict
  37. * PSet_, similar to set
  38. * PRecord_, a PMap on steroids with fixed fields, optional type and invariant checking and much more
  39. * PClass_, a Python class fixed fields, optional type and invariant checking and much more
  40. * `Checked collections`_, PVector, PMap and PSet with optional type and invariance checks and more
  41. * PBag, similar to collections.Counter
  42. * PList, a classic singly linked list
  43. * PDeque, similar to collections.deque
  44. * Immutable object type (immutable) built on the named tuple
  45. * freeze_ and thaw_ functions to convert between pythons standard collections and pyrsistent collections.
  46. * Flexible transformations_ of arbitrarily complex structures built from PMaps and PVectors.
  47. Below are examples of common usage patterns for some of the structures and features. More information and
  48. full documentation for all data structures is available in the documentation_.
  49. .. _PVector:
  50. PVector
  51. ~~~~~~~
  52. With full support for the Sequence_ protocol PVector is meant as a drop in replacement to the built in list from a readers
  53. point of view. Write operations of course differ since no in place mutation is done but naming should be in line
  54. with corresponding operations on the built in list.
  55. Support for the Hashable_ protocol also means that it can be used as key in Mappings_.
  56. Appends are amortized O(1). Random access and insert is log32(n) where n is the size of the vector.
  57. .. code:: python
  58. >>> from pyrsistent import v, pvector
  59. # No mutation of vectors once created, instead they
  60. # are "evolved" leaving the original untouched
  61. >>> v1 = v(1, 2, 3)
  62. >>> v2 = v1.append(4)
  63. >>> v3 = v2.set(1, 5)
  64. >>> v1
  65. pvector([1, 2, 3])
  66. >>> v2
  67. pvector([1, 2, 3, 4])
  68. >>> v3
  69. pvector([1, 5, 3, 4])
  70. # Random access and slicing
  71. >>> v3[1]
  72. 5
  73. >>> v3[1:3]
  74. pvector([5, 3])
  75. # Iteration
  76. >>> list(x + 1 for x in v3)
  77. [2, 6, 4, 5]
  78. >>> pvector(2 * x for x in range(3))
  79. pvector([0, 2, 4])
  80. .. _PMap:
  81. PMap
  82. ~~~~
  83. With full support for the Mapping_ protocol PMap is meant as a drop in replacement to the built in dict from a readers point
  84. of view. Support for the Hashable_ protocol also means that it can be used as key in other Mappings_.
  85. Random access and insert is log32(n) where n is the size of the map.
  86. .. code:: python
  87. >>> from pyrsistent import m, pmap, v
  88. # No mutation of maps once created, instead they are
  89. # "evolved" leaving the original untouched
  90. >>> m1 = m(a=1, b=2)
  91. >>> m2 = m1.set('c', 3)
  92. >>> m3 = m2.set('a', 5)
  93. >>> m1
  94. pmap({'a': 1, 'b': 2})
  95. >>> m2
  96. pmap({'a': 1, 'c': 3, 'b': 2})
  97. >>> m3
  98. pmap({'a': 5, 'c': 3, 'b': 2})
  99. >>> m3['a']
  100. 5
  101. # Evolution of nested persistent structures
  102. >>> m4 = m(a=5, b=6, c=v(1, 2))
  103. >>> m4.transform(('c', 1), 17)
  104. pmap({'a': 5, 'c': pvector([1, 17]), 'b': 6})
  105. >>> m5 = m(a=1, b=2)
  106. # Evolve by merging with other mappings
  107. >>> m5.update(m(a=2, c=3), {'a': 17, 'd': 35})
  108. pmap({'a': 17, 'c': 3, 'b': 2, 'd': 35})
  109. >>> pmap({'x': 1, 'y': 2}) + pmap({'y': 3, 'z': 4})
  110. pmap({'y': 3, 'x': 1, 'z': 4})
  111. # Dict-like methods to convert to list and iterate
  112. >>> m3.items()
  113. pvector([('a', 5), ('c', 3), ('b', 2)])
  114. >>> list(m3)
  115. ['a', 'c', 'b']
  116. .. _PSet:
  117. PSet
  118. ~~~~
  119. With full support for the Set_ protocol PSet is meant as a drop in replacement to the built in set from a readers point
  120. of view. Support for the Hashable_ protocol also means that it can be used as key in Mappings_.
  121. Random access and insert is log32(n) where n is the size of the set.
  122. .. code:: python
  123. >>> from pyrsistent import s
  124. # No mutation of sets once created, you know the story...
  125. >>> s1 = s(1, 2, 3, 2)
  126. >>> s2 = s1.add(4)
  127. >>> s3 = s1.remove(1)
  128. >>> s1
  129. pset([1, 2, 3])
  130. >>> s2
  131. pset([1, 2, 3, 4])
  132. >>> s3
  133. pset([2, 3])
  134. # Full support for set operations
  135. >>> s1 | s(3, 4, 5)
  136. pset([1, 2, 3, 4, 5])
  137. >>> s1 & s(3, 4, 5)
  138. pset([3])
  139. >>> s1 < s2
  140. True
  141. >>> s1 < s(3, 4, 5)
  142. False
  143. .. _PRecord:
  144. PRecord
  145. ~~~~~~~
  146. A PRecord is a PMap with a fixed set of specified fields. Records are declared as python classes inheriting
  147. from PRecord. Because it is a PMap it has full support for all Mapping methods such as iteration and element
  148. access using subscript notation.
  149. .. code:: python
  150. >>> from pyrsistent import PRecord, field
  151. >>> class ARecord(PRecord):
  152. ... x = field()
  153. ...
  154. >>> r = ARecord(x=3)
  155. >>> r
  156. ARecord(x=3)
  157. >>> r.x
  158. 3
  159. >>> r.set(x=2)
  160. ARecord(x=2)
  161. >>> r.set(y=2)
  162. Traceback (most recent call last):
  163. AttributeError: 'y' is not among the specified fields for ARecord
  164. Type information
  165. ****************
  166. It is possible to add type information to the record to enforce type checks. Multiple allowed types can be specified
  167. by providing an iterable of types.
  168. .. code:: python
  169. >>> class BRecord(PRecord):
  170. ... x = field(type=int)
  171. ... y = field(type=(int, type(None)))
  172. ...
  173. >>> BRecord(x=3, y=None)
  174. BRecord(y=None, x=3)
  175. >>> BRecord(x=3.0)
  176. Traceback (most recent call last):
  177. PTypeError: Invalid type for field BRecord.x, was float
  178. Custom types (classes) that are iterable should be wrapped in a tuple to prevent their
  179. members being added to the set of valid types. Although Enums in particular are now
  180. supported without wrapping, see #83 for more information.
  181. Mandatory fields
  182. ****************
  183. Fields are not mandatory by default but can be specified as such. If fields are missing an
  184. *InvariantException* will be thrown which contains information about the missing fields.
  185. .. code:: python
  186. >>> from pyrsistent import InvariantException
  187. >>> class CRecord(PRecord):
  188. ... x = field(mandatory=True)
  189. ...
  190. >>> r = CRecord(x=3)
  191. >>> try:
  192. ... r.discard('x')
  193. ... except InvariantException as e:
  194. ... print(e.missing_fields)
  195. ...
  196. ('CRecord.x',)
  197. Invariants
  198. **********
  199. It is possible to add invariants that must hold when evolving the record. Invariants can be
  200. specified on both field and record level. If invariants fail an *InvariantException* will be
  201. thrown which contains information about the failing invariants. An invariant function should
  202. return a tuple consisting of a boolean that tells if the invariant holds or not and an object
  203. describing the invariant. This object can later be used to identify which invariant that failed.
  204. The global invariant function is only executed if all field invariants hold.
  205. Global invariants are inherited to subclasses.
  206. .. code:: python
  207. >>> class RestrictedVector(PRecord):
  208. ... __invariant__ = lambda r: (r.y >= r.x, 'x larger than y')
  209. ... x = field(invariant=lambda x: (x > 0, 'x negative'))
  210. ... y = field(invariant=lambda y: (y > 0, 'y negative'))
  211. ...
  212. >>> r = RestrictedVector(y=3, x=2)
  213. >>> try:
  214. ... r.set(x=-1, y=-2)
  215. ... except InvariantException as e:
  216. ... print(e.invariant_errors)
  217. ...
  218. ('y negative', 'x negative')
  219. >>> try:
  220. ... r.set(x=2, y=1)
  221. ... except InvariantException as e:
  222. ... print(e.invariant_errors)
  223. ...
  224. ('x larger than y',)
  225. Invariants may also contain multiple assertions. For those cases the invariant function should
  226. return a tuple of invariant tuples as described above. This structure is reflected in the
  227. invariant_errors attribute of the exception which will contain tuples with data from all failed
  228. invariants. Eg:
  229. .. code:: python
  230. >>> class EvenX(PRecord):
  231. ... x = field(invariant=lambda x: ((x > 0, 'x negative'), (x % 2 == 0, 'x odd')))
  232. ...
  233. >>> try:
  234. ... EvenX(x=-1)
  235. ... except InvariantException as e:
  236. ... print(e.invariant_errors)
  237. ...
  238. (('x negative', 'x odd'),)
  239. Factories
  240. *********
  241. It's possible to specify factory functions for fields. The factory function receives whatever
  242. is supplied as field value and the actual returned by the factory is assigned to the field
  243. given that any type and invariant checks hold.
  244. PRecords have a default factory specified as a static function on the class, create(). It takes
  245. a *Mapping* as argument and returns an instance of the specific record.
  246. If a record has fields of type PRecord the create() method of that record will
  247. be called to create the "sub record" if no factory has explicitly been specified to override
  248. this behaviour.
  249. .. code:: python
  250. >>> class DRecord(PRecord):
  251. ... x = field(factory=int)
  252. ...
  253. >>> class ERecord(PRecord):
  254. ... d = field(type=DRecord)
  255. ...
  256. >>> ERecord.create({'d': {'x': '1'}})
  257. ERecord(d=DRecord(x=1))
  258. Collection fields
  259. *****************
  260. It is also possible to have fields with ``pyrsistent`` collections.
  261. .. code:: python
  262. >>> from pyrsistent import pset_field, pmap_field, pvector_field
  263. >>> class MultiRecord(PRecord):
  264. ... set_of_ints = pset_field(int)
  265. ... map_int_to_str = pmap_field(int, str)
  266. ... vector_of_strs = pvector_field(str)
  267. ...
  268. Serialization
  269. *************
  270. PRecords support serialization back to dicts. Default serialization will take keys and values
  271. "as is" and output them into a dict. It is possible to specify custom serialization functions
  272. to take care of fields that require special treatment.
  273. .. code:: python
  274. >>> from datetime import date
  275. >>> class Person(PRecord):
  276. ... name = field(type=unicode)
  277. ... birth_date = field(type=date,
  278. ... serializer=lambda format, d: d.strftime(format['date']))
  279. ...
  280. >>> john = Person(name=u'John', birth_date=date(1985, 10, 21))
  281. >>> john.serialize({'date': '%Y-%m-%d'})
  282. {'birth_date': '1985-10-21', 'name': u'John'}
  283. .. _instar: https://github.com/boxed/instar/
  284. .. _PClass:
  285. PClass
  286. ~~~~~~
  287. A PClass is a python class with a fixed set of specified fields. PClasses are declared as python classes inheriting
  288. from PClass. It is defined the same way that PRecords are and behaves like a PRecord in all aspects except that it
  289. is not a PMap and hence not a collection but rather a plain Python object.
  290. .. code:: python
  291. >>> from pyrsistent import PClass, field
  292. >>> class AClass(PClass):
  293. ... x = field()
  294. ...
  295. >>> a = AClass(x=3)
  296. >>> a
  297. AClass(x=3)
  298. >>> a.x
  299. 3
  300. Checked collections
  301. ~~~~~~~~~~~~~~~~~~~
  302. Checked collections currently come in three flavors: CheckedPVector, CheckedPMap and CheckedPSet.
  303. .. code:: python
  304. >>> from pyrsistent import CheckedPVector, CheckedPMap, CheckedPSet, thaw
  305. >>> class Positives(CheckedPSet):
  306. ... __type__ = (long, int)
  307. ... __invariant__ = lambda n: (n >= 0, 'Negative')
  308. ...
  309. >>> class Lottery(PRecord):
  310. ... name = field(type=str)
  311. ... numbers = field(type=Positives, invariant=lambda p: (len(p) > 0, 'No numbers'))
  312. ...
  313. >>> class Lotteries(CheckedPVector):
  314. ... __type__ = Lottery
  315. ...
  316. >>> class LotteriesByDate(CheckedPMap):
  317. ... __key_type__ = date
  318. ... __value_type__ = Lotteries
  319. ...
  320. >>> lotteries = LotteriesByDate.create({date(2015, 2, 15): [{'name': 'SuperLotto', 'numbers': {1, 2, 3}},
  321. ... {'name': 'MegaLotto', 'numbers': {4, 5, 6}}],
  322. ... date(2015, 2, 16): [{'name': 'SuperLotto', 'numbers': {3, 2, 1}},
  323. ... {'name': 'MegaLotto', 'numbers': {6, 5, 4}}]})
  324. >>> lotteries
  325. LotteriesByDate({datetime.date(2015, 2, 15): Lotteries([Lottery(numbers=Positives([1, 2, 3]), name='SuperLotto'), Lottery(numbers=Positives([4, 5, 6]), name='MegaLotto')]), datetime.date(2015, 2, 16): Lotteries([Lottery(numbers=Positives([1, 2, 3]), name='SuperLotto'), Lottery(numbers=Positives([4, 5, 6]), name='MegaLotto')])})
  326. # The checked versions support all operations that the corresponding
  327. # unchecked types do
  328. >>> lottery_0215 = lotteries[date(2015, 2, 15)]
  329. >>> lottery_0215.transform([0, 'name'], 'SuperDuperLotto')
  330. Lotteries([Lottery(numbers=Positives([1, 2, 3]), name='SuperDuperLotto'), Lottery(numbers=Positives([4, 5, 6]), name='MegaLotto')])
  331. # But also makes asserts that types and invariants hold
  332. >>> lottery_0215.transform([0, 'name'], 999)
  333. Traceback (most recent call last):
  334. PTypeError: Invalid type for field Lottery.name, was int
  335. >>> lottery_0215.transform([0, 'numbers'], set())
  336. Traceback (most recent call last):
  337. InvariantException: Field invariant failed
  338. # They can be converted back to python built ins with either thaw()
  339. # or serialize() (which provides possibilities to customize serialization)
  340. >>> thaw(lottery_0215)
  341. [{'numbers': set([1, 2, 3]), 'name': 'SuperLotto'}, {'numbers': set([4, 5, 6]), 'name': 'MegaLotto'}]
  342. >>> lottery_0215.serialize()
  343. [{'numbers': set([1, 2, 3]), 'name': 'SuperLotto'}, {'numbers': set([4, 5, 6]), 'name': 'MegaLotto'}]
  344. .. _transformations:
  345. Transformations
  346. ~~~~~~~~~~~~~~~
  347. Transformations are inspired by the cool library instar_ for Clojure. They let you evolve PMaps and PVectors
  348. with arbitrarily deep/complex nesting using simple syntax and flexible matching syntax.
  349. The first argument to transformation is the path that points out the value to transform. The
  350. second is the transformation to perform. If the transformation is callable it will be applied
  351. to the value(s) matching the path. The path may also contain callables. In that case they are
  352. treated as matchers. If the matcher returns True for a specific key it is considered for transformation.
  353. .. code:: python
  354. # Basic examples
  355. >>> from pyrsistent import inc, freeze, thaw, rex, ny, discard
  356. >>> v1 = freeze([1, 2, 3, 4, 5])
  357. >>> v1.transform([2], inc)
  358. pvector([1, 2, 4, 4, 5])
  359. >>> v1.transform([lambda ix: 0 < ix < 4], 8)
  360. pvector([1, 8, 8, 8, 5])
  361. >>> v1.transform([lambda ix, v: ix == 0 or v == 5], 0)
  362. pvector([0, 2, 3, 4, 0])
  363. # The (a)ny matcher can be used to match anything
  364. >>> v1.transform([ny], 8)
  365. pvector([8, 8, 8, 8, 8])
  366. # Regular expressions can be used for matching
  367. >>> scores = freeze({'John': 12, 'Joseph': 34, 'Sara': 23})
  368. >>> scores.transform([rex('^Jo')], 0)
  369. pmap({'Joseph': 0, 'Sara': 23, 'John': 0})
  370. # Transformations can be done on arbitrarily deep structures
  371. >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'},
  372. ... {'author': 'Steve', 'content': 'A slightly longer article'}],
  373. ... 'weather': {'temperature': '11C', 'wind': '5m/s'}})
  374. >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c)
  375. >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c)
  376. >>> very_short_news.articles[0].content
  377. 'A short article'
  378. >>> very_short_news.articles[1].content
  379. 'A slightly long...'
  380. # When nothing has been transformed the original data structure is kept
  381. >>> short_news is news_paper
  382. True
  383. >>> very_short_news is news_paper
  384. False
  385. >>> very_short_news.articles[0] is news_paper.articles[0]
  386. True
  387. # There is a special transformation that can be used to discard elements. Also
  388. # multiple transformations can be applied in one call
  389. >>> thaw(news_paper.transform(['weather'], discard, ['articles', ny, 'content'], discard))
  390. {'articles': [{'author': 'Sara'}, {'author': 'Steve'}]}
  391. Evolvers
  392. ~~~~~~~~
  393. PVector, PMap and PSet all have support for a concept dubbed *evolvers*. An evolver acts like a mutable
  394. view of the underlying persistent data structure with "transaction like" semantics. No updates of the original
  395. data structure is ever performed, it is still fully immutable.
  396. The evolvers have a very limited API by design to discourage excessive, and inappropriate, usage as that would
  397. take us down the mutable road. In principle only basic mutation and element access functions are supported.
  398. Check out the documentation_ of each data structure for specific examples.
  399. Examples of when you may want to use an evolver instead of working directly with the data structure include:
  400. * Multiple updates are done to the same data structure and the intermediate results are of no
  401. interest. In this case using an evolver may be a more efficient and easier to work with.
  402. * You need to pass a vector into a legacy function or a function that you have no control
  403. over which performs in place mutations. In this case pass an evolver instance
  404. instead and then create a new pvector from the evolver once the function returns.
  405. .. code:: python
  406. >>> from pyrsistent import v
  407. # In place mutation as when working with the built in counterpart
  408. >>> v1 = v(1, 2, 3)
  409. >>> e = v1.evolver()
  410. >>> e[1] = 22
  411. >>> e = e.append(4)
  412. >>> e = e.extend([5, 6])
  413. >>> e[5] += 1
  414. >>> len(e)
  415. 6
  416. # The evolver is considered *dirty* when it contains changes compared to the underlying vector
  417. >>> e.is_dirty()
  418. True
  419. # But the underlying pvector still remains untouched
  420. >>> v1
  421. pvector([1, 2, 3])
  422. # Once satisfied with the updates you can produce a new pvector containing the updates.
  423. # The new pvector will share data with the original pvector in the same way that would have
  424. # been done if only using operations on the pvector.
  425. >>> v2 = e.persistent()
  426. >>> v2
  427. pvector([1, 22, 3, 4, 5, 7])
  428. # The evolver is now no longer considered *dirty* as it contains no differences compared to the
  429. # pvector just produced.
  430. >>> e.is_dirty()
  431. False
  432. # You may continue to work with the same evolver without affecting the content of v2
  433. >>> e[0] = 11
  434. # Or create a new evolver from v2. The two evolvers can be updated independently but will both
  435. # share data with v2 where possible.
  436. >>> e2 = v2.evolver()
  437. >>> e2[0] = 1111
  438. >>> e.persistent()
  439. pvector([11, 22, 3, 4, 5, 7])
  440. >>> e2.persistent()
  441. pvector([1111, 22, 3, 4, 5, 7])
  442. .. _freeze:
  443. .. _thaw:
  444. freeze and thaw
  445. ~~~~~~~~~~~~~~~
  446. These functions are great when your cozy immutable world has to interact with the evil mutable world outside.
  447. .. code:: python
  448. >>> from pyrsistent import freeze, thaw, v, m
  449. >>> freeze([1, {'a': 3}])
  450. pvector([1, pmap({'a': 3})])
  451. >>> thaw(v(1, m(a=3)))
  452. [1, {'a': 3}]
  453. By default, freeze will also recursively convert values inside PVectors and PMaps. This behaviour can be changed by providing freeze with the flag strict=False.
  454. .. code:: python
  455. >>> from pyrsistent import freeze, v, m
  456. >>> freeze(v(1, v(2, [3])))
  457. pvector([1, pvector([2, pvector([3])])])
  458. >>> freeze(v(1, v(2, [3])), strict=False)
  459. pvector([1, pvector([2, [3]])])
  460. >>> freeze(m(a=m(b={'c': 1})))
  461. pmap({'a': pmap({'b': pmap({'c': 1})})})
  462. >>> freeze(m(a=m(b={'c': 1})), strict=False)
  463. pmap({'a': pmap({'b': {'c': 1}})})
  464. In this regard, thaw operates as the inverse of freeze so will thaw values inside native data structures unless passed the strict=False flag.
  465. Compatibility
  466. -------------
  467. Pyrsistent is developed and tested on Python 3.8+ and PyPy3.
  468. Performance
  469. -----------
  470. Pyrsistent is developed with performance in mind. Still, while some operations are nearly on par with their built in,
  471. mutable, counterparts in terms of speed, other operations are slower. In the cases where attempts at
  472. optimizations have been done, speed has generally been valued over space.
  473. Pyrsistent comes with two API compatible flavors of PVector (on which PMap and PSet are based), one pure Python
  474. implementation and one implemented as a C extension. The latter generally being 2 - 20 times faster than the former.
  475. The C extension will be used automatically when possible.
  476. The pure python implementation is fully PyPy compatible. Running it under PyPy speeds operations up considerably if
  477. the structures are used heavily (if JITed), for some cases the performance is almost on par with the built in counterparts.
  478. Type hints
  479. ----------
  480. PEP 561 style type hints for use with mypy and various editors are available for most types and functions in pyrsistent.
  481. Type classes for annotating your own code with pyrsistent types are also available under pyrsistent.typing.
  482. Installation
  483. ------------
  484. pip install pyrsistent
  485. Documentation
  486. -------------
  487. Available at http://pyrsistent.readthedocs.org/
  488. Brief presentation available at http://slides.com/tobiasgustafsson/immutability-and-python/
  489. Contributors
  490. ------------
  491. Tobias Gustafsson https://github.com/tobgu
  492. Christopher Armstrong https://github.com/radix
  493. Anders Hovmöller https://github.com/boxed
  494. Itamar Turner-Trauring https://github.com/itamarst
  495. Jonathan Lange https://github.com/jml
  496. Richard Futrell https://github.com/Futrell
  497. Jakob Hollenstein https://github.com/jkbjh
  498. David Honour https://github.com/foolswood
  499. David R. MacIver https://github.com/DRMacIver
  500. Marcus Ewert https://github.com/sarum90
  501. Jean-Paul Calderone https://github.com/exarkun
  502. Douglas Treadwell https://github.com/douglas-treadwell
  503. Travis Parker https://github.com/teepark
  504. Julian Berman https://github.com/Julian
  505. Dennis Tomas https://github.com/dtomas
  506. Neil Vyas https://github.com/neilvyas
  507. doozr https://github.com/doozr
  508. Kamil Galuszka https://github.com/galuszkak
  509. Tsuyoshi Hombashi https://github.com/thombashi
  510. nattofriends https://github.com/nattofriends
  511. agberk https://github.com/agberk
  512. Waleed Khan https://github.com/arxanas
  513. Jean-Louis Fuchs https://github.com/ganwell
  514. Carlos Corbacho https://github.com/ccorbacho
  515. Felix Yan https://github.com/felixonmars
  516. benrg https://github.com/benrg
  517. Jere Lahelma https://github.com/je-l
  518. Max Taggart https://github.com/MaxTaggart
  519. Vincent Philippon https://github.com/vphilippon
  520. Semen Zhydenko https://github.com/ss18
  521. Till Varoquaux https://github.com/till-varoquaux
  522. Michal Kowalik https://github.com/michalvi
  523. ossdev07 https://github.com/ossdev07
  524. Kerry Olesen https://github.com/qhesz
  525. johnthagen https://github.com/johnthagen
  526. Bastien Vallet https://github.com/djailla
  527. Ram Rachum https://github.com/cool-RR
  528. Vincent Philippon https://github.com/vphilippon
  529. Andrey Bienkowski https://github.com/hexagonrecursion
  530. Ethan McCue https://github.com/bowbahdoe
  531. Jason R. Coombs https://github.com/jaraco
  532. Nathan https://github.com/ndowens
  533. Geert Barentsen https://github.com/barentsen
  534. phil-arh https://github.com/phil-arh
  535. Tamás Nepusz https://github.com/ntamas
  536. Hugo van Kemenade https://github.com/hugovk
  537. Ben Beasley https://github.com/musicinmybrain
  538. Noah C. Benson https://github.com/noahbenson
  539. dscrofts https://github.com/dscrofts
  540. Andy Reagan https://github.com/andyreagan
  541. Aaron Durant https://github.com/Aaron-Durant
  542. Joshua Munn https://github.com/jams2
  543. Lukas https://github.com/lukasK9999
  544. Arshad https://github.com/arshad-ml
  545. Contributing
  546. ------------
  547. Want to contribute? That's great! If you experience problems please log them on GitHub. If you want to contribute code,
  548. please fork the repository and submit a pull request.
  549. Run tests
  550. ~~~~~~~~~
  551. .. _tox: https://tox.readthedocs.io/en/latest/
  552. Tests can be executed using tox_.
  553. Install tox: ``pip install tox``
  554. Run test for Python 3.8: ``tox -e py38``
  555. Release
  556. ~~~~~~~
  557. * `pip install -r requirements.txt`
  558. * Update CHANGES.txt
  559. * Update README.rst with any new contributors and potential info needed.
  560. * Update _pyrsistent_version.py
  561. * Commit and tag with new version: `git add -u . && git commit -m 'Prepare version vX.Y.Z' && git tag -a vX.Y.Z -m 'vX.Y.Z'`
  562. * Push commit and tags: `git push --follow-tags`
  563. * Build new release using Github actions
  564. Project status
  565. --------------
  566. Pyrsistent can be considered stable and mature (who knows, there may even be a 1.0 some day :-)). The project is
  567. maintained, bugs fixed, PRs reviewed and merged and new releases made. I currently do not have time for development
  568. of new features or functionality which I don't have use for myself. I'm more than happy to take PRs for new
  569. functionality though!
  570. There are a bunch of issues marked with ``enhancement`` and ``help wanted`` that contain requests for new functionality
  571. that would be nice to include. The level of difficulty and extend of the issues varies, please reach out to me if you're
  572. interested in working on any of them.
  573. If you feel that you have a grand master plan for where you would like Pyrsistent to go and have the time to put into
  574. it please don't hesitate to discuss this with me and submit PRs for it. If all goes well I'd be more than happy to add
  575. additional maintainers to the project!