iterutils.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Mahmoud Hashemi
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. # * The names of the contributors may not be used to endorse or
  17. # promote products derived from this software without specific
  18. # prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """:mod:`itertools` is full of great examples of Python generator
  32. usage. However, there are still some critical gaps. ``iterutils``
  33. fills many of those gaps with featureful, tested, and Pythonic
  34. solutions.
  35. Many of the functions below have two versions, one which
  36. returns an iterator (denoted by the ``*_iter`` naming pattern), and a
  37. shorter-named convenience form that returns a list. Some of the
  38. following are based on examples in itertools docs.
  39. """
  40. import os
  41. import math
  42. import time
  43. import codecs
  44. import random
  45. import itertools
  46. try:
  47. from collections.abc import Mapping, Sequence, Set, ItemsView, Iterable
  48. except ImportError:
  49. from collections import Mapping, Sequence, Set, ItemsView, Iterable
  50. try:
  51. from .typeutils import make_sentinel
  52. _UNSET = make_sentinel('_UNSET')
  53. _REMAP_EXIT = make_sentinel('_REMAP_EXIT')
  54. except ImportError:
  55. _REMAP_EXIT = object()
  56. _UNSET = object()
  57. try:
  58. from future_builtins import filter
  59. from itertools import izip
  60. _IS_PY3 = False
  61. except ImportError:
  62. # Python 3 compat
  63. _IS_PY3 = True
  64. basestring = (str, bytes)
  65. unicode = str
  66. izip, xrange = zip, range
  67. def is_iterable(obj):
  68. """Similar in nature to :func:`callable`, ``is_iterable`` returns
  69. ``True`` if an object is `iterable`_, ``False`` if not.
  70. >>> is_iterable([])
  71. True
  72. >>> is_iterable(object())
  73. False
  74. .. _iterable: https://docs.python.org/2/glossary.html#term-iterable
  75. """
  76. try:
  77. iter(obj)
  78. except TypeError:
  79. return False
  80. return True
  81. def is_scalar(obj):
  82. """A near-mirror of :func:`is_iterable`. Returns ``False`` if an
  83. object is an iterable container type. Strings are considered
  84. scalar as well, because strings are more often treated as whole
  85. values as opposed to iterables of 1-character substrings.
  86. >>> is_scalar(object())
  87. True
  88. >>> is_scalar(range(10))
  89. False
  90. >>> is_scalar('hello')
  91. True
  92. """
  93. return not is_iterable(obj) or isinstance(obj, basestring)
  94. def is_collection(obj):
  95. """The opposite of :func:`is_scalar`. Returns ``True`` if an object
  96. is an iterable other than a string.
  97. >>> is_collection(object())
  98. False
  99. >>> is_collection(range(10))
  100. True
  101. >>> is_collection('hello')
  102. False
  103. """
  104. return is_iterable(obj) and not isinstance(obj, basestring)
  105. def split(src, sep=None, maxsplit=None):
  106. """Splits an iterable based on a separator. Like :meth:`str.split`,
  107. but for all iterables. Returns a list of lists.
  108. >>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None])
  109. [['hi', 'hello'], ['sup'], ['soap']]
  110. See :func:`split_iter` docs for more info.
  111. """
  112. return list(split_iter(src, sep, maxsplit))
  113. def split_iter(src, sep=None, maxsplit=None):
  114. """Splits an iterable based on a separator, *sep*, a max of
  115. *maxsplit* times (no max by default). *sep* can be:
  116. * a single value
  117. * an iterable of separators
  118. * a single-argument callable that returns True when a separator is
  119. encountered
  120. ``split_iter()`` yields lists of non-separator values. A separator will
  121. never appear in the output.
  122. >>> list(split_iter(['hi', 'hello', None, None, 'sup', None, 'soap', None]))
  123. [['hi', 'hello'], ['sup'], ['soap']]
  124. Note that ``split_iter`` is based on :func:`str.split`, so if
  125. *sep* is ``None``, ``split()`` **groups** separators. If empty lists
  126. are desired between two contiguous ``None`` values, simply use
  127. ``sep=[None]``:
  128. >>> list(split_iter(['hi', 'hello', None, None, 'sup', None]))
  129. [['hi', 'hello'], ['sup']]
  130. >>> list(split_iter(['hi', 'hello', None, None, 'sup', None], sep=[None]))
  131. [['hi', 'hello'], [], ['sup'], []]
  132. Using a callable separator:
  133. >>> falsy_sep = lambda x: not x
  134. >>> list(split_iter(['hi', 'hello', None, '', 'sup', False], falsy_sep))
  135. [['hi', 'hello'], [], ['sup'], []]
  136. See :func:`split` for a list-returning version.
  137. """
  138. if not is_iterable(src):
  139. raise TypeError('expected an iterable')
  140. if maxsplit is not None:
  141. maxsplit = int(maxsplit)
  142. if maxsplit == 0:
  143. yield [src]
  144. return
  145. if callable(sep):
  146. sep_func = sep
  147. elif not is_scalar(sep):
  148. sep = frozenset(sep)
  149. sep_func = lambda x: x in sep
  150. else:
  151. sep_func = lambda x: x == sep
  152. cur_group = []
  153. split_count = 0
  154. for s in src:
  155. if maxsplit is not None and split_count >= maxsplit:
  156. sep_func = lambda x: False
  157. if sep_func(s):
  158. if sep is None and not cur_group:
  159. # If sep is none, str.split() "groups" separators
  160. # check the str.split() docs for more info
  161. continue
  162. split_count += 1
  163. yield cur_group
  164. cur_group = []
  165. else:
  166. cur_group.append(s)
  167. if cur_group or sep is not None:
  168. yield cur_group
  169. return
  170. def lstrip(iterable, strip_value=None):
  171. """Strips values from the beginning of an iterable. Stripped items will
  172. match the value of the argument strip_value. Functionality is analogous
  173. to that of the method str.lstrip. Returns a list.
  174. >>> lstrip(['Foo', 'Bar', 'Bam'], 'Foo')
  175. ['Bar', 'Bam']
  176. """
  177. return list(lstrip_iter(iterable, strip_value))
  178. def lstrip_iter(iterable, strip_value=None):
  179. """Strips values from the beginning of an iterable. Stripped items will
  180. match the value of the argument strip_value. Functionality is analogous
  181. to that of the method str.lstrip. Returns a generator.
  182. >>> list(lstrip_iter(['Foo', 'Bar', 'Bam'], 'Foo'))
  183. ['Bar', 'Bam']
  184. """
  185. iterator = iter(iterable)
  186. for i in iterator:
  187. if i != strip_value:
  188. yield i
  189. break
  190. for i in iterator:
  191. yield i
  192. def rstrip(iterable, strip_value=None):
  193. """Strips values from the end of an iterable. Stripped items will
  194. match the value of the argument strip_value. Functionality is analogous
  195. to that of the method str.rstrip. Returns a list.
  196. >>> rstrip(['Foo', 'Bar', 'Bam'], 'Bam')
  197. ['Foo', 'Bar']
  198. """
  199. return list(rstrip_iter(iterable,strip_value))
  200. def rstrip_iter(iterable, strip_value=None):
  201. """Strips values from the end of an iterable. Stripped items will
  202. match the value of the argument strip_value. Functionality is analogous
  203. to that of the method str.rstrip. Returns a generator.
  204. >>> list(rstrip_iter(['Foo', 'Bar', 'Bam'], 'Bam'))
  205. ['Foo', 'Bar']
  206. """
  207. iterator = iter(iterable)
  208. for i in iterator:
  209. if i == strip_value:
  210. cache = list()
  211. cache.append(i)
  212. broken = False
  213. for i in iterator:
  214. if i == strip_value:
  215. cache.append(i)
  216. else:
  217. broken = True
  218. break
  219. if not broken: # Return to caller here because the end of the
  220. return # iterator has been reached
  221. for t in cache:
  222. yield t
  223. yield i
  224. def strip(iterable, strip_value=None):
  225. """Strips values from the beginning and end of an iterable. Stripped items
  226. will match the value of the argument strip_value. Functionality is
  227. analogous to that of the method str.strip. Returns a list.
  228. >>> strip(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu')
  229. ['Foo', 'Bar', 'Bam']
  230. """
  231. return list(strip_iter(iterable,strip_value))
  232. def strip_iter(iterable,strip_value=None):
  233. """Strips values from the beginning and end of an iterable. Stripped items
  234. will match the value of the argument strip_value. Functionality is
  235. analogous to that of the method str.strip. Returns a generator.
  236. >>> list(strip_iter(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu'))
  237. ['Foo', 'Bar', 'Bam']
  238. """
  239. return rstrip_iter(lstrip_iter(iterable,strip_value),strip_value)
  240. def chunked(src, size, count=None, **kw):
  241. """Returns a list of *count* chunks, each with *size* elements,
  242. generated from iterable *src*. If *src* is not evenly divisible by
  243. *size*, the final chunk will have fewer than *size* elements.
  244. Provide the *fill* keyword argument to provide a pad value and
  245. enable padding, otherwise no padding will take place.
  246. >>> chunked(range(10), 3)
  247. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
  248. >>> chunked(range(10), 3, fill=None)
  249. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]
  250. >>> chunked(range(10), 3, count=2)
  251. [[0, 1, 2], [3, 4, 5]]
  252. See :func:`chunked_iter` for more info.
  253. """
  254. chunk_iter = chunked_iter(src, size, **kw)
  255. if count is None:
  256. return list(chunk_iter)
  257. else:
  258. return list(itertools.islice(chunk_iter, count))
  259. def _validate_positive_int(value, name, strictly_positive=True):
  260. value = int(value)
  261. if value < 0 or (strictly_positive and value == 0):
  262. raise ValueError('expected a positive integer ' + name)
  263. return value
  264. def chunked_iter(src, size, **kw):
  265. """Generates *size*-sized chunks from *src* iterable. Unless the
  266. optional *fill* keyword argument is provided, iterables not evenly
  267. divisible by *size* will have a final chunk that is smaller than
  268. *size*.
  269. >>> list(chunked_iter(range(10), 3))
  270. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
  271. >>> list(chunked_iter(range(10), 3, fill=None))
  272. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]
  273. Note that ``fill=None`` in fact uses ``None`` as the fill value.
  274. """
  275. # TODO: add count kwarg?
  276. if not is_iterable(src):
  277. raise TypeError('expected an iterable')
  278. size = _validate_positive_int(size, 'chunk size')
  279. do_fill = True
  280. try:
  281. fill_val = kw.pop('fill')
  282. except KeyError:
  283. do_fill = False
  284. fill_val = None
  285. if kw:
  286. raise ValueError('got unexpected keyword arguments: %r' % kw.keys())
  287. if not src:
  288. return
  289. postprocess = lambda chk: chk
  290. if isinstance(src, basestring):
  291. postprocess = lambda chk, _sep=type(src)(): _sep.join(chk)
  292. if _IS_PY3 and isinstance(src, bytes):
  293. postprocess = lambda chk: bytes(chk)
  294. src_iter = iter(src)
  295. while True:
  296. cur_chunk = list(itertools.islice(src_iter, size))
  297. if not cur_chunk:
  298. break
  299. lc = len(cur_chunk)
  300. if lc < size and do_fill:
  301. cur_chunk[lc:] = [fill_val] * (size - lc)
  302. yield postprocess(cur_chunk)
  303. return
  304. def chunk_ranges(input_size, chunk_size, input_offset=0, overlap_size=0, align=False):
  305. """Generates *chunk_size*-sized chunk ranges for an input with length *input_size*.
  306. Optionally, a start of the input can be set via *input_offset*, and
  307. and overlap between the chunks may be specified via *overlap_size*.
  308. Also, if *align* is set to *True*, any items with *i % (chunk_size-overlap_size) == 0*
  309. are always at the beginning of the chunk.
  310. Returns an iterator of (start, end) tuples, one tuple per chunk.
  311. >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5))
  312. [(10, 15), (15, 20)]
  313. >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=1))
  314. [(10, 15), (14, 19), (18, 20)]
  315. >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=2))
  316. [(10, 15), (13, 18), (16, 20)]
  317. >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=False))
  318. [(4, 9), (9, 14), (14, 19)]
  319. >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=True))
  320. [(4, 5), (5, 10), (10, 15), (15, 19)]
  321. >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=False))
  322. [(2, 7), (6, 11), (10, 15), (14, 17)]
  323. >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=True))
  324. [(2, 5), (4, 9), (8, 13), (12, 17)]
  325. >>> list(chunk_ranges(input_offset=3, input_size=15, chunk_size=5, overlap_size=1, align=True))
  326. [(3, 5), (4, 9), (8, 13), (12, 17), (16, 18)]
  327. """
  328. input_size = _validate_positive_int(input_size, 'input_size', strictly_positive=False)
  329. chunk_size = _validate_positive_int(chunk_size, 'chunk_size')
  330. input_offset = _validate_positive_int(input_offset, 'input_offset', strictly_positive=False)
  331. overlap_size = _validate_positive_int(overlap_size, 'overlap_size', strictly_positive=False)
  332. input_stop = input_offset + input_size
  333. if align:
  334. initial_chunk_len = chunk_size - input_offset % (chunk_size - overlap_size)
  335. if initial_chunk_len != overlap_size:
  336. yield (input_offset, min(input_offset + initial_chunk_len, input_stop))
  337. if input_offset + initial_chunk_len >= input_stop:
  338. return
  339. input_offset = input_offset + initial_chunk_len - overlap_size
  340. for i in range(input_offset, input_stop, chunk_size - overlap_size):
  341. yield (i, min(i + chunk_size, input_stop))
  342. if i + chunk_size >= input_stop:
  343. return
  344. def pairwise(src):
  345. """Convenience function for calling :func:`windowed` on *src*, with
  346. *size* set to 2.
  347. >>> pairwise(range(5))
  348. [(0, 1), (1, 2), (2, 3), (3, 4)]
  349. >>> pairwise([])
  350. []
  351. The number of pairs is always one less than the number of elements
  352. in the iterable passed in, except on empty inputs, which returns
  353. an empty list.
  354. """
  355. return windowed(src, 2)
  356. def pairwise_iter(src):
  357. """Convenience function for calling :func:`windowed_iter` on *src*,
  358. with *size* set to 2.
  359. >>> list(pairwise_iter(range(5)))
  360. [(0, 1), (1, 2), (2, 3), (3, 4)]
  361. >>> list(pairwise_iter([]))
  362. []
  363. The number of pairs is always one less than the number of elements
  364. in the iterable passed in, or zero, when *src* is empty.
  365. """
  366. return windowed_iter(src, 2)
  367. def windowed(src, size):
  368. """Returns tuples with exactly length *size*. If the iterable is
  369. too short to make a window of length *size*, no tuples are
  370. returned. See :func:`windowed_iter` for more.
  371. """
  372. return list(windowed_iter(src, size))
  373. def windowed_iter(src, size):
  374. """Returns tuples with length *size* which represent a sliding
  375. window over iterable *src*.
  376. >>> list(windowed_iter(range(7), 3))
  377. [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
  378. If the iterable is too short to make a window of length *size*,
  379. then no window tuples are returned.
  380. >>> list(windowed_iter(range(3), 5))
  381. []
  382. """
  383. # TODO: lists? (for consistency)
  384. tees = itertools.tee(src, size)
  385. try:
  386. for i, t in enumerate(tees):
  387. for _ in xrange(i):
  388. next(t)
  389. except StopIteration:
  390. return izip([])
  391. return izip(*tees)
  392. def xfrange(stop, start=None, step=1.0):
  393. """Same as :func:`frange`, but generator-based instead of returning a
  394. list.
  395. >>> tuple(xfrange(1, 3, step=0.75))
  396. (1.0, 1.75, 2.5)
  397. See :func:`frange` for more details.
  398. """
  399. if not step:
  400. raise ValueError('step must be non-zero')
  401. if start is None:
  402. start, stop = 0.0, stop * 1.0
  403. else:
  404. # swap when all args are used
  405. stop, start = start * 1.0, stop * 1.0
  406. cur = start
  407. while cur < stop:
  408. yield cur
  409. cur += step
  410. def frange(stop, start=None, step=1.0):
  411. """A :func:`range` clone for float-based ranges.
  412. >>> frange(5)
  413. [0.0, 1.0, 2.0, 3.0, 4.0]
  414. >>> frange(6, step=1.25)
  415. [0.0, 1.25, 2.5, 3.75, 5.0]
  416. >>> frange(100.5, 101.5, 0.25)
  417. [100.5, 100.75, 101.0, 101.25]
  418. >>> frange(5, 0)
  419. []
  420. >>> frange(5, 0, step=-1.25)
  421. [5.0, 3.75, 2.5, 1.25]
  422. """
  423. if not step:
  424. raise ValueError('step must be non-zero')
  425. if start is None:
  426. start, stop = 0.0, stop * 1.0
  427. else:
  428. # swap when all args are used
  429. stop, start = start * 1.0, stop * 1.0
  430. count = int(math.ceil((stop - start) / step))
  431. ret = [None] * count
  432. if not ret:
  433. return ret
  434. ret[0] = start
  435. for i in xrange(1, count):
  436. ret[i] = ret[i - 1] + step
  437. return ret
  438. def backoff(start, stop, count=None, factor=2.0, jitter=False):
  439. """Returns a list of geometrically-increasing floating-point numbers,
  440. suitable for usage with `exponential backoff`_. Exactly like
  441. :func:`backoff_iter`, but without the ``'repeat'`` option for
  442. *count*. See :func:`backoff_iter` for more details.
  443. .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff
  444. >>> backoff(1, 10)
  445. [1.0, 2.0, 4.0, 8.0, 10.0]
  446. """
  447. if count == 'repeat':
  448. raise ValueError("'repeat' supported in backoff_iter, not backoff")
  449. return list(backoff_iter(start, stop, count=count,
  450. factor=factor, jitter=jitter))
  451. def backoff_iter(start, stop, count=None, factor=2.0, jitter=False):
  452. """Generates a sequence of geometrically-increasing floats, suitable
  453. for usage with `exponential backoff`_. Starts with *start*,
  454. increasing by *factor* until *stop* is reached, optionally
  455. stopping iteration once *count* numbers are yielded. *factor*
  456. defaults to 2. In general retrying with properly-configured
  457. backoff creates a better-behaved component for a larger service
  458. ecosystem.
  459. .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff
  460. >>> list(backoff_iter(1.0, 10.0, count=5))
  461. [1.0, 2.0, 4.0, 8.0, 10.0]
  462. >>> list(backoff_iter(1.0, 10.0, count=8))
  463. [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0]
  464. >>> list(backoff_iter(0.25, 100.0, factor=10))
  465. [0.25, 2.5, 25.0, 100.0]
  466. A simplified usage example:
  467. .. code-block:: python
  468. for timeout in backoff_iter(0.25, 5.0):
  469. try:
  470. res = network_call()
  471. break
  472. except Exception as e:
  473. log(e)
  474. time.sleep(timeout)
  475. An enhancement for large-scale systems would be to add variation,
  476. or *jitter*, to timeout values. This is done to avoid a thundering
  477. herd on the receiving end of the network call.
  478. Finally, for *count*, the special value ``'repeat'`` can be passed to
  479. continue yielding indefinitely.
  480. Args:
  481. start (float): Positive number for baseline.
  482. stop (float): Positive number for maximum.
  483. count (int): Number of steps before stopping
  484. iteration. Defaults to the number of steps between *start* and
  485. *stop*. Pass the string, `'repeat'`, to continue iteration
  486. indefinitely.
  487. factor (float): Rate of exponential increase. Defaults to `2.0`,
  488. e.g., `[1, 2, 4, 8, 16]`.
  489. jitter (float): A factor between `-1.0` and `1.0`, used to
  490. uniformly randomize and thus spread out timeouts in a distributed
  491. system, avoiding rhythm effects. Positive values use the base
  492. backoff curve as a maximum, negative values use the curve as a
  493. minimum. Set to 1.0 or `True` for a jitter approximating
  494. Ethernet's time-tested backoff solution. Defaults to `False`.
  495. """
  496. start = float(start)
  497. stop = float(stop)
  498. factor = float(factor)
  499. if start < 0.0:
  500. raise ValueError('expected start >= 0, not %r' % start)
  501. if factor < 1.0:
  502. raise ValueError('expected factor >= 1.0, not %r' % factor)
  503. if stop == 0.0:
  504. raise ValueError('expected stop >= 0')
  505. if stop < start:
  506. raise ValueError('expected stop >= start, not %r' % stop)
  507. if count is None:
  508. denom = start if start else 1
  509. count = 1 + math.ceil(math.log(stop/denom, factor))
  510. count = count if start else count + 1
  511. if count != 'repeat' and count < 0:
  512. raise ValueError('count must be positive or "repeat", not %r' % count)
  513. if jitter:
  514. jitter = float(jitter)
  515. if not (-1.0 <= jitter <= 1.0):
  516. raise ValueError('expected jitter -1 <= j <= 1, not: %r' % jitter)
  517. cur, i = start, 0
  518. while count == 'repeat' or i < count:
  519. if not jitter:
  520. cur_ret = cur
  521. elif jitter:
  522. cur_ret = cur - (cur * jitter * random.random())
  523. yield cur_ret
  524. i += 1
  525. if cur == 0:
  526. cur = 1
  527. elif cur < stop:
  528. cur *= factor
  529. if cur > stop:
  530. cur = stop
  531. return
  532. def bucketize(src, key=bool, value_transform=None, key_filter=None):
  533. """Group values in the *src* iterable by the value returned by *key*.
  534. >>> bucketize(range(5))
  535. {False: [0], True: [1, 2, 3, 4]}
  536. >>> is_odd = lambda x: x % 2 == 1
  537. >>> bucketize(range(5), is_odd)
  538. {False: [0, 2, 4], True: [1, 3]}
  539. *key* is :class:`bool` by default, but can either be a callable or a string or a list
  540. if it is a string, it is the name of the attribute on which to bucketize objects.
  541. >>> bucketize([1+1j, 2+2j, 1, 2], key='real')
  542. {1.0: [(1+1j), 1], 2.0: [(2+2j), 2]}
  543. if *key* is a list, it contains the buckets where to put each object
  544. >>> bucketize([1,2,365,4,98],key=[0,1,2,0,2])
  545. {0: [1, 4], 1: [2], 2: [365, 98]}
  546. Value lists are not deduplicated:
  547. >>> bucketize([None, None, None, 'hello'])
  548. {False: [None, None, None], True: ['hello']}
  549. Bucketize into more than 3 groups
  550. >>> bucketize(range(10), lambda x: x % 3)
  551. {0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}
  552. ``bucketize`` has a couple of advanced options useful in certain
  553. cases. *value_transform* can be used to modify values as they are
  554. added to buckets, and *key_filter* will allow excluding certain
  555. buckets from being collected.
  556. >>> bucketize(range(5), value_transform=lambda x: x*x)
  557. {False: [0], True: [1, 4, 9, 16]}
  558. >>> bucketize(range(10), key=lambda x: x % 3, key_filter=lambda k: k % 3 != 1)
  559. {0: [0, 3, 6, 9], 2: [2, 5, 8]}
  560. Note in some of these examples there were at most two keys, ``True`` and
  561. ``False``, and each key present has a list with at least one
  562. item. See :func:`partition` for a version specialized for binary
  563. use cases.
  564. """
  565. if not is_iterable(src):
  566. raise TypeError('expected an iterable')
  567. elif isinstance(key, list):
  568. if len(key) != len(src):
  569. raise ValueError("key and src have to be the same length")
  570. src = zip(key, src)
  571. if isinstance(key, basestring):
  572. key_func = lambda x: getattr(x, key, x)
  573. elif callable(key):
  574. key_func = key
  575. elif isinstance(key, list):
  576. key_func = lambda x: x[0]
  577. else:
  578. raise TypeError('expected key to be callable or a string or a list')
  579. if value_transform is None:
  580. value_transform = lambda x: x
  581. if not callable(value_transform):
  582. raise TypeError('expected callable value transform function')
  583. if isinstance(key, list):
  584. f = value_transform
  585. value_transform=lambda x: f(x[1])
  586. ret = {}
  587. for val in src:
  588. key_of_val = key_func(val)
  589. if key_filter is None or key_filter(key_of_val):
  590. ret.setdefault(key_of_val, []).append(value_transform(val))
  591. return ret
  592. def partition(src, key=bool):
  593. """No relation to :meth:`str.partition`, ``partition`` is like
  594. :func:`bucketize`, but for added convenience returns a tuple of
  595. ``(truthy_values, falsy_values)``.
  596. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye'])
  597. >>> nonempty
  598. ['hi', 'bye']
  599. *key* defaults to :class:`bool`, but can be carefully overridden to
  600. use either a function that returns either ``True`` or ``False`` or
  601. a string name of the attribute on which to partition objects.
  602. >>> import string
  603. >>> is_digit = lambda x: x in string.digits
  604. >>> decimal_digits, hexletters = partition(string.hexdigits, is_digit)
  605. >>> ''.join(decimal_digits), ''.join(hexletters)
  606. ('0123456789', 'abcdefABCDEF')
  607. """
  608. bucketized = bucketize(src, key)
  609. return bucketized.get(True, []), bucketized.get(False, [])
  610. def unique(src, key=None):
  611. """``unique()`` returns a list of unique values, as determined by
  612. *key*, in the order they first appeared in the input iterable,
  613. *src*.
  614. >>> ones_n_zeros = '11010110001010010101010'
  615. >>> ''.join(unique(ones_n_zeros))
  616. '10'
  617. See :func:`unique_iter` docs for more details.
  618. """
  619. return list(unique_iter(src, key))
  620. def unique_iter(src, key=None):
  621. """Yield unique elements from the iterable, *src*, based on *key*,
  622. in the order in which they first appeared in *src*.
  623. >>> repetitious = [1, 2, 3] * 10
  624. >>> list(unique_iter(repetitious))
  625. [1, 2, 3]
  626. By default, *key* is the object itself, but *key* can either be a
  627. callable or, for convenience, a string name of the attribute on
  628. which to uniqueify objects, falling back on identity when the
  629. attribute is not present.
  630. >>> pleasantries = ['hi', 'hello', 'ok', 'bye', 'yes']
  631. >>> list(unique_iter(pleasantries, key=lambda x: len(x)))
  632. ['hi', 'hello', 'bye']
  633. """
  634. if not is_iterable(src):
  635. raise TypeError('expected an iterable, not %r' % type(src))
  636. if key is None:
  637. key_func = lambda x: x
  638. elif callable(key):
  639. key_func = key
  640. elif isinstance(key, basestring):
  641. key_func = lambda x: getattr(x, key, x)
  642. else:
  643. raise TypeError('"key" expected a string or callable, not %r' % key)
  644. seen = set()
  645. for i in src:
  646. k = key_func(i)
  647. if k not in seen:
  648. seen.add(k)
  649. yield i
  650. return
  651. def redundant(src, key=None, groups=False):
  652. """The complement of :func:`unique()`.
  653. By default returns non-unique/duplicate values as a list of the
  654. *first* redundant value in *src*. Pass ``groups=True`` to get
  655. groups of all values with redundancies, ordered by position of the
  656. first redundant value. This is useful in conjunction with some
  657. normalizing *key* function.
  658. >>> redundant([1, 2, 3, 4])
  659. []
  660. >>> redundant([1, 2, 3, 2, 3, 3, 4])
  661. [2, 3]
  662. >>> redundant([1, 2, 3, 2, 3, 3, 4], groups=True)
  663. [[2, 2], [3, 3, 3]]
  664. An example using a *key* function to do case-insensitive
  665. redundancy detection.
  666. >>> redundant(['hi', 'Hi', 'HI', 'hello'], key=str.lower)
  667. ['Hi']
  668. >>> redundant(['hi', 'Hi', 'HI', 'hello'], groups=True, key=str.lower)
  669. [['hi', 'Hi', 'HI']]
  670. *key* should also be used when the values in *src* are not hashable.
  671. .. note::
  672. This output of this function is designed for reporting
  673. duplicates in contexts when a unique input is desired. Due to
  674. the grouped return type, there is no streaming equivalent of
  675. this function for the time being.
  676. """
  677. if key is None:
  678. pass
  679. elif callable(key):
  680. key_func = key
  681. elif isinstance(key, basestring):
  682. key_func = lambda x: getattr(x, key, x)
  683. else:
  684. raise TypeError('"key" expected a string or callable, not %r' % key)
  685. seen = {} # key to first seen item
  686. redundant_order = []
  687. redundant_groups = {}
  688. for i in src:
  689. k = key_func(i) if key else i
  690. if k not in seen:
  691. seen[k] = i
  692. else:
  693. if k in redundant_groups:
  694. if groups:
  695. redundant_groups[k].append(i)
  696. else:
  697. redundant_order.append(k)
  698. redundant_groups[k] = [seen[k], i]
  699. if not groups:
  700. ret = [redundant_groups[k][1] for k in redundant_order]
  701. else:
  702. ret = [redundant_groups[k] for k in redundant_order]
  703. return ret
  704. def one(src, default=None, key=None):
  705. """Along the same lines as builtins, :func:`all` and :func:`any`, and
  706. similar to :func:`first`, ``one()`` returns the single object in
  707. the given iterable *src* that evaluates to ``True``, as determined
  708. by callable *key*. If unset, *key* defaults to :class:`bool`. If
  709. no such objects are found, *default* is returned. If *default* is
  710. not passed, ``None`` is returned.
  711. If *src* has more than one object that evaluates to ``True``, or
  712. if there is no object that fulfills such condition, return
  713. *default*. It's like an `XOR`_ over an iterable.
  714. >>> one((True, False, False))
  715. True
  716. >>> one((True, False, True))
  717. >>> one((0, 0, 'a'))
  718. 'a'
  719. >>> one((0, False, None))
  720. >>> one((True, True), default=False)
  721. False
  722. >>> bool(one(('', 1)))
  723. True
  724. >>> one((10, 20, 30, 42), key=lambda i: i > 40)
  725. 42
  726. See `Martín Gaitán's original repo`_ for further use cases.
  727. .. _Martín Gaitán's original repo: https://github.com/mgaitan/one
  728. .. _XOR: https://en.wikipedia.org/wiki/Exclusive_or
  729. """
  730. ones = list(itertools.islice(filter(key, src), 2))
  731. return ones[0] if len(ones) == 1 else default
  732. def first(iterable, default=None, key=None):
  733. """Return first element of *iterable* that evaluates to ``True``, else
  734. return ``None`` or optional *default*. Similar to :func:`one`.
  735. >>> first([0, False, None, [], (), 42])
  736. 42
  737. >>> first([0, False, None, [], ()]) is None
  738. True
  739. >>> first([0, False, None, [], ()], default='ohai')
  740. 'ohai'
  741. >>> import re
  742. >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
  743. >>> m.group(1)
  744. 'bc'
  745. The optional *key* argument specifies a one-argument predicate function
  746. like that used for *filter()*. The *key* argument, if supplied, should be
  747. in keyword form. For example, finding the first even number in an iterable:
  748. >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
  749. 4
  750. Contributed by Hynek Schlawack, author of `the original standalone module`_.
  751. .. _the original standalone module: https://github.com/hynek/first
  752. """
  753. return next(filter(key, iterable), default)
  754. def flatten_iter(iterable):
  755. """``flatten_iter()`` yields all the elements from *iterable* while
  756. collapsing any nested iterables.
  757. >>> nested = [[1, 2], [[3], [4, 5]]]
  758. >>> list(flatten_iter(nested))
  759. [1, 2, 3, 4, 5]
  760. """
  761. for item in iterable:
  762. if isinstance(item, Iterable) and not isinstance(item, basestring):
  763. for subitem in flatten_iter(item):
  764. yield subitem
  765. else:
  766. yield item
  767. def flatten(iterable):
  768. """``flatten()`` returns a collapsed list of all the elements from
  769. *iterable* while collapsing any nested iterables.
  770. >>> nested = [[1, 2], [[3], [4, 5]]]
  771. >>> flatten(nested)
  772. [1, 2, 3, 4, 5]
  773. """
  774. return list(flatten_iter(iterable))
  775. def same(iterable, ref=_UNSET):
  776. """``same()`` returns ``True`` when all values in *iterable* are
  777. equal to one another, or optionally a reference value,
  778. *ref*. Similar to :func:`all` and :func:`any` in that it evaluates
  779. an iterable and returns a :class:`bool`. ``same()`` returns
  780. ``True`` for empty iterables.
  781. >>> same([])
  782. True
  783. >>> same([1])
  784. True
  785. >>> same(['a', 'a', 'a'])
  786. True
  787. >>> same(range(20))
  788. False
  789. >>> same([[], []])
  790. True
  791. >>> same([[], []], ref='test')
  792. False
  793. """
  794. iterator = iter(iterable)
  795. if ref is _UNSET:
  796. ref = next(iterator, ref)
  797. return all(val == ref for val in iterator)
  798. def default_visit(path, key, value):
  799. # print('visit(%r, %r, %r)' % (path, key, value))
  800. return key, value
  801. # enable the extreme: monkeypatching iterutils with a different default_visit
  802. _orig_default_visit = default_visit
  803. def default_enter(path, key, value):
  804. # print('enter(%r, %r)' % (key, value))
  805. if isinstance(value, basestring):
  806. return value, False
  807. elif isinstance(value, Mapping):
  808. return value.__class__(), ItemsView(value)
  809. elif isinstance(value, Sequence):
  810. return value.__class__(), enumerate(value)
  811. elif isinstance(value, Set):
  812. return value.__class__(), enumerate(value)
  813. else:
  814. # files, strings, other iterables, and scalars are not
  815. # traversed
  816. return value, False
  817. def default_exit(path, key, old_parent, new_parent, new_items):
  818. # print('exit(%r, %r, %r, %r, %r)'
  819. # % (path, key, old_parent, new_parent, new_items))
  820. ret = new_parent
  821. if isinstance(new_parent, Mapping):
  822. new_parent.update(new_items)
  823. elif isinstance(new_parent, Sequence):
  824. vals = [v for i, v in new_items]
  825. try:
  826. new_parent.extend(vals)
  827. except AttributeError:
  828. ret = new_parent.__class__(vals) # tuples
  829. elif isinstance(new_parent, Set):
  830. vals = [v for i, v in new_items]
  831. try:
  832. new_parent.update(vals)
  833. except AttributeError:
  834. ret = new_parent.__class__(vals) # frozensets
  835. else:
  836. raise RuntimeError('unexpected iterable type: %r' % type(new_parent))
  837. return ret
  838. def remap(root, visit=default_visit, enter=default_enter, exit=default_exit,
  839. **kwargs):
  840. """The remap ("recursive map") function is used to traverse and
  841. transform nested structures. Lists, tuples, sets, and dictionaries
  842. are just a few of the data structures nested into heterogeneous
  843. tree-like structures that are so common in programming.
  844. Unfortunately, Python's built-in ways to manipulate collections
  845. are almost all flat. List comprehensions may be fast and succinct,
  846. but they do not recurse, making it tedious to apply quick changes
  847. or complex transforms to real-world data.
  848. remap goes where list comprehensions cannot.
  849. Here's an example of removing all Nones from some data:
  850. >>> from pprint import pprint
  851. >>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None},
  852. ... 'Babylon 5': 6, 'Dr. Who': None}
  853. >>> pprint(remap(reviews, lambda p, k, v: v is not None))
  854. {'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}}
  855. Notice how both Nones have been removed despite the nesting in the
  856. dictionary. Not bad for a one-liner, and that's just the beginning.
  857. See `this remap cookbook`_ for more delicious recipes.
  858. .. _this remap cookbook: http://sedimental.org/remap.html
  859. remap takes four main arguments: the object to traverse and three
  860. optional callables which determine how the remapped object will be
  861. created.
  862. Args:
  863. root: The target object to traverse. By default, remap
  864. supports iterables like :class:`list`, :class:`tuple`,
  865. :class:`dict`, and :class:`set`, but any object traversable by
  866. *enter* will work.
  867. visit (callable): This function is called on every item in
  868. *root*. It must accept three positional arguments, *path*,
  869. *key*, and *value*. *path* is simply a tuple of parents'
  870. keys. *visit* should return the new key-value pair. It may
  871. also return ``True`` as shorthand to keep the old item
  872. unmodified, or ``False`` to drop the item from the new
  873. structure. *visit* is called after *enter*, on the new parent.
  874. The *visit* function is called for every item in root,
  875. including duplicate items. For traversable values, it is
  876. called on the new parent object, after all its children
  877. have been visited. The default visit behavior simply
  878. returns the key-value pair unmodified.
  879. enter (callable): This function controls which items in *root*
  880. are traversed. It accepts the same arguments as *visit*: the
  881. path, the key, and the value of the current item. It returns a
  882. pair of the blank new parent, and an iterator over the items
  883. which should be visited. If ``False`` is returned instead of
  884. an iterator, the value will not be traversed.
  885. The *enter* function is only called once per unique value. The
  886. default enter behavior support mappings, sequences, and
  887. sets. Strings and all other iterables will not be traversed.
  888. exit (callable): This function determines how to handle items
  889. once they have been visited. It gets the same three
  890. arguments as the other functions -- *path*, *key*, *value*
  891. -- plus two more: the blank new parent object returned
  892. from *enter*, and a list of the new items, as remapped by
  893. *visit*.
  894. Like *enter*, the *exit* function is only called once per
  895. unique value. The default exit behavior is to simply add
  896. all new items to the new parent, e.g., using
  897. :meth:`list.extend` and :meth:`dict.update` to add to the
  898. new parent. Immutable objects, such as a :class:`tuple` or
  899. :class:`namedtuple`, must be recreated from scratch, but
  900. use the same type as the new parent passed back from the
  901. *enter* function.
  902. reraise_visit (bool): A pragmatic convenience for the *visit*
  903. callable. When set to ``False``, remap ignores any errors
  904. raised by the *visit* callback. Items causing exceptions
  905. are kept. See examples for more details.
  906. remap is designed to cover the majority of cases with just the
  907. *visit* callable. While passing in multiple callables is very
  908. empowering, remap is designed so very few cases should require
  909. passing more than one function.
  910. When passing *enter* and *exit*, it's common and easiest to build
  911. on the default behavior. Simply add ``from boltons.iterutils import
  912. default_enter`` (or ``default_exit``), and have your enter/exit
  913. function call the default behavior before or after your custom
  914. logic. See `this example`_.
  915. Duplicate and self-referential objects (aka reference loops) are
  916. automatically handled internally, `as shown here`_.
  917. .. _this example: http://sedimental.org/remap.html#sort_all_lists
  918. .. _as shown here: http://sedimental.org/remap.html#corner_cases
  919. """
  920. # TODO: improve argument formatting in sphinx doc
  921. # TODO: enter() return (False, items) to continue traverse but cancel copy?
  922. if not callable(visit):
  923. raise TypeError('visit expected callable, not: %r' % visit)
  924. if not callable(enter):
  925. raise TypeError('enter expected callable, not: %r' % enter)
  926. if not callable(exit):
  927. raise TypeError('exit expected callable, not: %r' % exit)
  928. reraise_visit = kwargs.pop('reraise_visit', True)
  929. if kwargs:
  930. raise TypeError('unexpected keyword arguments: %r' % kwargs.keys())
  931. path, registry, stack = (), {}, [(None, root)]
  932. new_items_stack = []
  933. while stack:
  934. key, value = stack.pop()
  935. id_value = id(value)
  936. if key is _REMAP_EXIT:
  937. key, new_parent, old_parent = value
  938. id_value = id(old_parent)
  939. path, new_items = new_items_stack.pop()
  940. value = exit(path, key, old_parent, new_parent, new_items)
  941. registry[id_value] = value
  942. if not new_items_stack:
  943. continue
  944. elif id_value in registry:
  945. value = registry[id_value]
  946. else:
  947. res = enter(path, key, value)
  948. try:
  949. new_parent, new_items = res
  950. except TypeError:
  951. # TODO: handle False?
  952. raise TypeError('enter should return a tuple of (new_parent,'
  953. ' items_iterator), not: %r' % res)
  954. if new_items is not False:
  955. # traverse unless False is explicitly passed
  956. registry[id_value] = new_parent
  957. new_items_stack.append((path, []))
  958. if value is not root:
  959. path += (key,)
  960. stack.append((_REMAP_EXIT, (key, new_parent, value)))
  961. if new_items:
  962. stack.extend(reversed(list(new_items)))
  963. continue
  964. if visit is _orig_default_visit:
  965. # avoid function call overhead by inlining identity operation
  966. visited_item = (key, value)
  967. else:
  968. try:
  969. visited_item = visit(path, key, value)
  970. except Exception:
  971. if reraise_visit:
  972. raise
  973. visited_item = True
  974. if visited_item is False:
  975. continue # drop
  976. elif visited_item is True:
  977. visited_item = (key, value)
  978. # TODO: typecheck?
  979. # raise TypeError('expected (key, value) from visit(),'
  980. # ' not: %r' % visited_item)
  981. try:
  982. new_items_stack[-1][1].append(visited_item)
  983. except IndexError:
  984. raise TypeError('expected remappable root, not: %r' % root)
  985. return value
  986. class PathAccessError(KeyError, IndexError, TypeError):
  987. """An amalgamation of KeyError, IndexError, and TypeError,
  988. representing what can occur when looking up a path in a nested
  989. object.
  990. """
  991. def __init__(self, exc, seg, path):
  992. self.exc = exc
  993. self.seg = seg
  994. self.path = path
  995. def __repr__(self):
  996. cn = self.__class__.__name__
  997. return '%s(%r, %r, %r)' % (cn, self.exc, self.seg, self.path)
  998. def __str__(self):
  999. return ('could not access %r from path %r, got error: %r'
  1000. % (self.seg, self.path, self.exc))
  1001. def get_path(root, path, default=_UNSET):
  1002. """Retrieve a value from a nested object via a tuple representing the
  1003. lookup path.
  1004. >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
  1005. >>> get_path(root, ('a', 'b', 'c', 2, 0))
  1006. 3
  1007. The path format is intentionally consistent with that of
  1008. :func:`remap`.
  1009. One of get_path's chief aims is improved error messaging. EAFP is
  1010. great, but the error messages are not.
  1011. For instance, ``root['a']['b']['c'][2][1]`` gives back
  1012. ``IndexError: list index out of range``
  1013. What went out of range where? get_path currently raises
  1014. ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2,
  1015. 1), got error: IndexError('list index out of range',)``, a
  1016. subclass of IndexError and KeyError.
  1017. You can also pass a default that covers the entire operation,
  1018. should the lookup fail at any level.
  1019. Args:
  1020. root: The target nesting of dictionaries, lists, or other
  1021. objects supporting ``__getitem__``.
  1022. path (tuple): A list of strings and integers to be successively
  1023. looked up within *root*.
  1024. default: The value to be returned should any
  1025. ``PathAccessError`` exceptions be raised.
  1026. """
  1027. if isinstance(path, basestring):
  1028. path = path.split('.')
  1029. cur = root
  1030. try:
  1031. for seg in path:
  1032. try:
  1033. cur = cur[seg]
  1034. except (KeyError, IndexError) as exc:
  1035. raise PathAccessError(exc, seg, path)
  1036. except TypeError as exc:
  1037. # either string index in a list, or a parent that
  1038. # doesn't support indexing
  1039. try:
  1040. seg = int(seg)
  1041. cur = cur[seg]
  1042. except (ValueError, KeyError, IndexError, TypeError):
  1043. if not is_iterable(cur):
  1044. exc = TypeError('%r object is not indexable'
  1045. % type(cur).__name__)
  1046. raise PathAccessError(exc, seg, path)
  1047. except PathAccessError:
  1048. if default is _UNSET:
  1049. raise
  1050. return default
  1051. return cur
  1052. def research(root, query=lambda p, k, v: True, reraise=False):
  1053. """The :func:`research` function uses :func:`remap` to recurse over
  1054. any data nested in *root*, and find values which match a given
  1055. criterion, specified by the *query* callable.
  1056. Results are returned as a list of ``(path, value)`` pairs. The
  1057. paths are tuples in the same format accepted by
  1058. :func:`get_path`. This can be useful for comparing values nested
  1059. in two or more different structures.
  1060. Here's a simple example that finds all integers:
  1061. >>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None}
  1062. >>> res = research(root, query=lambda p, k, v: isinstance(v, int))
  1063. >>> print(sorted(res))
  1064. [(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)]
  1065. Note how *query* follows the same, familiar ``path, key, value``
  1066. signature as the ``visit`` and ``enter`` functions on
  1067. :func:`remap`, and returns a :class:`bool`.
  1068. Args:
  1069. root: The target object to search. Supports the same types of
  1070. objects as :func:`remap`, including :class:`list`,
  1071. :class:`tuple`, :class:`dict`, and :class:`set`.
  1072. query (callable): The function called on every object to
  1073. determine whether to include it in the search results. The
  1074. callable must accept three arguments, *path*, *key*, and
  1075. *value*, commonly abbreviated *p*, *k*, and *v*, same as
  1076. *enter* and *visit* from :func:`remap`.
  1077. reraise (bool): Whether to reraise exceptions raised by *query*
  1078. or to simply drop the result that caused the error.
  1079. With :func:`research` it's easy to inspect the details of a data
  1080. structure, like finding values that are at a certain depth (using
  1081. ``len(p)``) and much more. If more advanced functionality is
  1082. needed, check out the code and make your own :func:`remap`
  1083. wrapper, and consider `submitting a patch`_!
  1084. .. _submitting a patch: https://github.com/mahmoud/boltons/pulls
  1085. """
  1086. ret = []
  1087. if not callable(query):
  1088. raise TypeError('query expected callable, not: %r' % query)
  1089. def enter(path, key, value):
  1090. try:
  1091. if query(path, key, value):
  1092. ret.append((path + (key,), value))
  1093. except Exception:
  1094. if reraise:
  1095. raise
  1096. return default_enter(path, key, value)
  1097. remap(root, enter=enter)
  1098. return ret
  1099. # TODO: recollect()
  1100. # TODO: refilter()
  1101. # TODO: reiter()
  1102. # GUID iterators: 10x faster and somewhat more compact than uuid.
  1103. class GUIDerator(object):
  1104. """The GUIDerator is an iterator that yields a globally-unique
  1105. identifier (GUID) on every iteration. The GUIDs produced are
  1106. hexadecimal strings.
  1107. Testing shows it to be around 12x faster than the uuid module. By
  1108. default it is also more compact, partly due to its default 96-bit
  1109. (24-hexdigit) length. 96 bits of randomness means that there is a
  1110. 1 in 2 ^ 32 chance of collision after 2 ^ 64 iterations. If more
  1111. or less uniqueness is desired, the *size* argument can be adjusted
  1112. accordingly.
  1113. Args:
  1114. size (int): character length of the GUID, defaults to 24. Lengths
  1115. between 20 and 36 are considered valid.
  1116. The GUIDerator has built-in fork protection that causes it to
  1117. detect a fork on next iteration and reseed accordingly.
  1118. """
  1119. def __init__(self, size=24):
  1120. self.size = size
  1121. if size < 20 or size > 36:
  1122. raise ValueError('expected 20 < size <= 36')
  1123. import hashlib
  1124. self._sha1 = hashlib.sha1
  1125. self.count = itertools.count()
  1126. self.reseed()
  1127. def reseed(self):
  1128. import socket
  1129. self.pid = os.getpid()
  1130. self.salt = '-'.join([str(self.pid),
  1131. socket.gethostname() or b'<nohostname>',
  1132. str(time.time()),
  1133. codecs.encode(os.urandom(6),
  1134. 'hex_codec').decode('ascii')])
  1135. # that codecs trick is the best/only way to get a bytes to
  1136. # hexbytes in py2/3
  1137. return
  1138. def __iter__(self):
  1139. return self
  1140. if _IS_PY3:
  1141. def __next__(self):
  1142. if os.getpid() != self.pid:
  1143. self.reseed()
  1144. target_bytes = (self.salt + str(next(self.count))).encode('utf8')
  1145. hash_text = self._sha1(target_bytes).hexdigest()[:self.size]
  1146. return hash_text
  1147. else:
  1148. def __next__(self):
  1149. if os.getpid() != self.pid:
  1150. self.reseed()
  1151. return self._sha1(self.salt +
  1152. str(next(self.count))).hexdigest()[:self.size]
  1153. next = __next__
  1154. class SequentialGUIDerator(GUIDerator):
  1155. """Much like the standard GUIDerator, the SequentialGUIDerator is an
  1156. iterator that yields a globally-unique identifier (GUID) on every
  1157. iteration. The GUIDs produced are hexadecimal strings.
  1158. The SequentialGUIDerator differs in that it picks a starting GUID
  1159. value and increments every iteration. This yields GUIDs which are
  1160. of course unique, but also ordered and lexicographically sortable.
  1161. The SequentialGUIDerator is around 50% faster than the normal
  1162. GUIDerator, making it almost 20x as fast as the built-in uuid
  1163. module. By default it is also more compact, partly due to its
  1164. 96-bit (24-hexdigit) default length. 96 bits of randomness means that
  1165. there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64
  1166. iterations. If more or less uniqueness is desired, the *size*
  1167. argument can be adjusted accordingly.
  1168. Args:
  1169. size (int): character length of the GUID, defaults to 24.
  1170. Note that with SequentialGUIDerator there is a chance of GUIDs
  1171. growing larger than the size configured. The SequentialGUIDerator
  1172. has built-in fork protection that causes it to detect a fork on
  1173. next iteration and reseed accordingly.
  1174. """
  1175. if _IS_PY3:
  1176. def reseed(self):
  1177. super(SequentialGUIDerator, self).reseed()
  1178. start_str = self._sha1(self.salt.encode('utf8')).hexdigest()
  1179. self.start = int(start_str[:self.size], 16)
  1180. self.start |= (1 << ((self.size * 4) - 2))
  1181. else:
  1182. def reseed(self):
  1183. super(SequentialGUIDerator, self).reseed()
  1184. start_str = self._sha1(self.salt).hexdigest()
  1185. self.start = int(start_str[:self.size], 16)
  1186. self.start |= (1 << ((self.size * 4) - 2))
  1187. def __next__(self):
  1188. if os.getpid() != self.pid:
  1189. self.reseed()
  1190. return '%x' % (next(self.count) + self.start)
  1191. next = __next__
  1192. guid_iter = GUIDerator()
  1193. seq_guid_iter = SequentialGUIDerator()
  1194. def soft_sorted(iterable, first=None, last=None, key=None, reverse=False):
  1195. """For when you care about the order of some elements, but not about
  1196. others.
  1197. Use this to float to the top and/or sink to the bottom a specific
  1198. ordering, while sorting the rest of the elements according to
  1199. normal :func:`sorted` rules.
  1200. >>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two'])
  1201. ['one', 'two', 'a', 'b']
  1202. >>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True)
  1203. [6, 5, 3, 1, 0, 2, 4]
  1204. >>> import string
  1205. >>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower))
  1206. 'aA1023456789cCdDeEfFbB'
  1207. Args:
  1208. iterable (list): A list or other iterable to sort.
  1209. first (list): A sequence to enforce for elements which should
  1210. appear at the beginning of the returned list.
  1211. last (list): A sequence to enforce for elements which should
  1212. appear at the end of the returned list.
  1213. key (callable): Callable used to generate a comparable key for
  1214. each item to be sorted, same as the key in
  1215. :func:`sorted`. Note that entries in *first* and *last*
  1216. should be the keys for the items. Defaults to
  1217. passthrough/the identity function.
  1218. reverse (bool): Whether or not elements not explicitly ordered
  1219. by *first* and *last* should be in reverse order or not.
  1220. Returns a new list in sorted order.
  1221. """
  1222. first = first or []
  1223. last = last or []
  1224. key = key or (lambda x: x)
  1225. seq = list(iterable)
  1226. other = [x for x in seq if not ((first and key(x) in first) or (last and key(x) in last))]
  1227. other.sort(key=key, reverse=reverse)
  1228. if first:
  1229. first = sorted([x for x in seq if key(x) in first], key=lambda x: first.index(key(x)))
  1230. if last:
  1231. last = sorted([x for x in seq if key(x) in last], key=lambda x: last.index(key(x)))
  1232. return first + other + last
  1233. def untyped_sorted(iterable, key=None, reverse=False):
  1234. """A version of :func:`sorted` which will happily sort an iterable of
  1235. heterogeneous types and return a new list, similar to legacy Python's
  1236. behavior.
  1237. >>> untyped_sorted(['abc', 2.0, 1, 2, 'def'])
  1238. [1, 2.0, 2, 'abc', 'def']
  1239. Note how mutually orderable types are sorted as expected, as in
  1240. the case of the integers and floats above.
  1241. .. note::
  1242. Results may vary across Python versions and builds, but the
  1243. function will produce a sorted list, except in the case of
  1244. explicitly unorderable objects.
  1245. """
  1246. class _Wrapper(object):
  1247. slots = ('obj',)
  1248. def __init__(self, obj):
  1249. self.obj = obj
  1250. def __lt__(self, other):
  1251. obj = key(self.obj) if key is not None else self.obj
  1252. other = key(other.obj) if key is not None else other.obj
  1253. try:
  1254. ret = obj < other
  1255. except TypeError:
  1256. ret = ((type(obj).__name__, id(type(obj)), obj)
  1257. < (type(other).__name__, id(type(other)), other))
  1258. return ret
  1259. if key is not None and not callable(key):
  1260. raise TypeError('expected function or callable object for key, not: %r'
  1261. % key)
  1262. return sorted(iterable, key=_Wrapper, reverse=reverse)
  1263. """
  1264. May actually be faster to do an isinstance check for a str path
  1265. $ python -m timeit -s "x = [1]" "x[0]"
  1266. 10000000 loops, best of 3: 0.0207 usec per loop
  1267. $ python -m timeit -s "x = [1]" "try: x[0] \nexcept: pass"
  1268. 10000000 loops, best of 3: 0.029 usec per loop
  1269. $ python -m timeit -s "x = [1]" "try: x[1] \nexcept: pass"
  1270. 1000000 loops, best of 3: 0.315 usec per loop
  1271. # setting up try/except is fast, only around 0.01us
  1272. # actually triggering the exception takes almost 10x as long
  1273. $ python -m timeit -s "x = [1]" "isinstance(x, basestring)"
  1274. 10000000 loops, best of 3: 0.141 usec per loop
  1275. $ python -m timeit -s "x = [1]" "isinstance(x, str)"
  1276. 10000000 loops, best of 3: 0.131 usec per loop
  1277. $ python -m timeit -s "x = [1]" "try: x.split('.')\n except: pass"
  1278. 1000000 loops, best of 3: 0.443 usec per loop
  1279. $ python -m timeit -s "x = [1]" "try: x.split('.') \nexcept AttributeError: pass"
  1280. 1000000 loops, best of 3: 0.544 usec per loop
  1281. """