METADATA 27 KB

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