-
Notifications
You must be signed in to change notification settings - Fork 0
/
awmstools.py
2045 lines (1699 loc) · 59.1 KB
/
awmstools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
#############################################################################
################## awmstools : Common functions for python ###################
##############################################################################
##
## o author: Alexander Schmolck ([email protected])
## o created: 2000-04-08T15:52:17+00:00
## o last changed: $Date: 2009-03-24 02:09:50 $
## o license: see file LICENSE
## o keywords: python, helper functions
## o requires: python >= 2.4
## o TODO:
## - get rid of the bogus test failure (doctest: +ELLIPSIS)
## - streamline or cull baroque stuff like reverse
## - cull more stuff and factor into several files
## - saveVars etc. should have `silent` option or so
## - not all functions are tested rigorously yet
## - write a fast merge (kicked old slow recursive one)
##
## Sorted in inverse order of uselessness :) The stuff under EXPERIMENTAL is
## just that: experimental. Expect it not to work, or to disappear or to be
## incompatibly modified in the future. The rest should be fairly stable.
"""A collection of various convenience functions and classes, small utilities
and 'fixes'.
Some just save a little bit of typing (`Result`), others are things that
seem to have been forgotten in the standard libraries (`slurp`,
`binarySearch`, `replaceStrs`) or that have a strange behavior
(`os.path.splitext`). Apart from several general purpose utilities for
lists (`flatten`) iterables in general (`window`, `unique`, `union`,
`group` etc.) there are also more special purpose utilities such as various
handy functions and classes for writing scripts (`DryRun`), for debugging
(`makePrintReturner`) and for meta-programming (`gensym`).
"""
__docformat__ = "restructuredtext en"
__revision__ = "$Id: awmstools.py,v 1.29 2009-03-24 02:09:50 aschmolc Exp $"
__version__ = "0.9"
__author__ = "Alexander Schmolck <[email protected]>"
__test__ = {} # this is for doctest
import bisect
import codecs
import copy
import pickle
import collections
from functools import reduce
try: from functools import partial # python < 2.5 compatibility
except ImportError: partial = lambda f,*args,**kwargs: lambda *a,**k: f(args+a,update(kwargs,k))
from itertools import *
import inspect
import itertools
import math
import operator
import os
from subprocess import Popen
import getpass
import re
import sys
import tempfile
import time
import types
import urllib.request, urllib.error, urllib.parse
try: from threading import Lock
except ImportError: Lock = lambda: Null
try: any
except NameError: any = lambda xs: bool(some(xs)); all = lambda xs: bool(every(xs))
class _uniqueClass(object):
"""To create a single instance to be used for default values; supports
comparison by-object identity to work around stupid classes that won't allow
comparisons to non-self-instances."""
def __eq__(a,b): return a is b;
def __ne__(a,b): return a is not b
try: # don't redefine on reload
__unique
except NameError:
__unique = _uniqueClass()
if sys.maxsize > 1e6*60*60*24*365*100: # see below
# XXX this relies on the GIL & itertools for threadsafety
# but since itertools.count can only count to sys.maxint...
def Counter(start=0):
"""A threadsafe counter that let's you keep counting
for at least 100 years at a rate of 1MHz (if `start`= 0).
"""
return itertools.count(start).__next__
else:
# ... we also need this more generic version
class Counter(object):
"""A threadsafe counter that let's you keep counting
for at least 100 years at a rate of 10^6/s (if `start`= 0).
"""
def __init__(self, start=0):
self.lock = Lock()
self.count = start
def __call__(self):
try:
self.lock.acquire()
return self.count
finally:
self.count+=1
self.lock.release()
# don't redefine on reload
try:
_count
except NameError:
_count = Counter()
_gensyms = {}
def gensym(prefix="GSYM"):
r"""Returns an string that is valid as a unique python variable name. Useful
when creating functions etc. on the fly. Can be used from multiple threads
and is `reload` safe.
"""
return "%s%d" % (prefix, _count())
__test__['gensym'] = r"""
>>> import awmstools
>>> bak = awmstools._count
>>> awmstools._count = Counter()
>>> gensym()
'GSYM0'
>>> gensym()
'GSYM1'
>>> gensym('FOO')
'FOO2'
>>> import awmstools
>>> reload(awmstools) and None
>>> awmstools._count = bak
"""
# FIXME test threadsafety at least superficially!
#_. FIXES
# Fixes for things in python I'd like to behave differently
def rexGroups(rex):
"""Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)')
('name', 'surname')
"""
if isinstance(rex,str): rex = re.compile(rex)
return zip(*sorted([(n,g) for (g,n) in list(rex.groupindex.items())]))[1]
class IndexMaker(object):
"""Convinience class to make slices etc. that can be used for creating
indices (mainly because using `slice` is a PITA).
Examples:
>>> range(4)[indexme[::-1]] == range(4)[::-1] == [3, 2, 1, 0]
True
>>> indexme[::-1]
slice(None, None, -1)
>>> indexme[0,:]
(0, slice(None, None, None))
"""
def __getitem__(self, a):
return a
indexme = IndexMaker()
# A shortcut for 'infinite' integer e.g. for slicing: ``seq[4:INFI]`` as
# ``seq[4:len(seq)]`` is messy and only works if `seq` isn't an expression
INFI = sys.maxsize
# real infinity
INF = 1e999999
class Result(object):
"""Circumvent python's lack of assignment expression (mainly useful for
writing while loops):
>>> import re
>>> s = 'one 2 three 4 five 6'
>>> findNumber = Result(re.compile('\d+').search)
>>> while findNumber(s):
... match = findNumber.result
... print 'found', `match.group(0)`, 'at position', match.start()
... s = s[match.end():]
...
found '2' at position 4
found '4' at position 7
found '6' at position 6
"""
def __init__(self, func):
self.func = func
def __call__(self,*args,**kwargs):
self.result = self.func(*args,**kwargs)
return self.result
class NullType(object):
r"""Similar to `NoneType` with a corresponding singleton instance `Null`
that, unlike `None` accepts any message and returns itself.
Examples:
>>> Null("send", a="message")(*"and one more")[
... "even index and"].what.you.get.still is Null
True
>>> not Null
True
>>> Null['something']
Null
>>> Null.something
Null
>>> Null in Null
False
>>> hasattr(Null, 'something')
True
>>> Null.something = "a value"
>>> Null.something
Null
>>> Null == Null
True
>>> Null == 3
False
"""
def __new__(cls): return Null
def __call__(self, *args, **kwargs): return Null
## def __getstate__(self, *args): return Null
def __getinitargs__(self):
print("__getinitargs__")
return ('foobar',)
def __getattr__(self, attr): return Null
def __getitem__(self, item): return Null
def __setattr__(self, attr, value): pass
def __setitem__(self, item, value): pass
def __len__(self): return 0
def __iter__(self): return iter([])
def __contains__(self, item): return False
def __repr__(self): return "Null"
Null = object.__new__(NullType)
def div(a,b):
"""``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10
"""
res, fail = divmod(a,b)
if fail:
raise ValueError("%r does not divide %r" % (b,a))
else:
return res
def ipshuffle(l, random=None):
r"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l
__test__['ipshuffle'] = r'''
>>> l = [1,2,3]
>>> ipshuffle(l, lambda :0.3) is l
True
>>> l
[2, 3, 1]
>>> l = [1,2,3]
>>> ipshuffle(l, lambda :0.4) is l
True
>>> l
[3, 1, 2]
'''
def shuffle(seq, random=None):
r"""Return shuffled *copy* of `seq`."""
if isinstance(seq, list):
return ipshuffle(seq[:], random)
elif isString(seq):
# seq[0:0] == "" or u""
return seq[0:0].join(ipshuffle(list(seq)),random)
else:
return type(seq)(ipshuffle(list(seq),random))
__test__['shuffle'] = r'''
>>> l = [1,2,3]
>>> shuffle(l, lambda :0.3)
[2, 3, 1]
>>> l
[1, 2, 3]
>>> shuffle(l, lambda :0.4)
[3, 1, 2]
>>> l
[1, 2, 3]
'''
# s = open(file).read() would be a nice shorthand -- unfortunately it doesn't
# work (because the file is never properly closed, at least not under
# Jython). Thus:
def _normalizeToFile(maybeFile, mode, expand):
if isinstance(maybeFile, int):
return os.fdopen(maybeFile, mode)
elif isString(maybeFile):
if maybeFile.startswith('http://'): #XXX experimental
return urllib.request.urlopen(maybeFile)
else:
if expand:
maybeFile = os.path.expandvars(os.path.expanduser(maybeFile))
return open(maybeFile, mode)
else:
return maybeFile
def slurp(file, binary=False, expand=False):
r"""Read in a complete file `file` as a string
Parameters:
- `file`: a file handle or a string (`str` or `unicode`).
- `binary`: whether to read in the file in binary mode (default: False).
"""
mode = "r" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return file.read()
finally: file.close()
# FIXME write proper tests for IO stuff
def withFile(file, func, mode='r', expand=False):
"""Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a string, open according to `mode`; if `expand` is true also
expand user and vars.
"""
file = _normalizeToFile(file, mode=mode, expand=expand)
try: return func(file)
finally: file.close()
def slurpLines(file, expand=False):
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines"""
file = _normalizeToFile(file, "r", expand)
try: return file.readlines()
finally: file.close()
def slurpChompedLines(file, expand=False):
r"""Return ``file`` a list of chomped lines. See `slurpLines`."""
f=_normalizeToFile(file, "r", expand)
try: return list(chompLines(f))
finally: f.close()
def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False):
"""Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`.
"""
fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in
[('suffix',suffix),('prefix',prefix),('dir', dir)]
if v is not None))
spitOut(s, fd, binary)
return filename
def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close()
def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close()
#FIXME should use new subprocess module if possible
def readProcess(cmd, *args):
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes.
"""
BUFSIZE=1024
import select
popen = Popen((cmd,) + args, capturestderr=True)
which = {id(popen.fromchild): [],
id(popen.childerr): []}
select = Result(select.select)
read = Result(os.read)
try:
popen.tochild.close() # XXX make sure we're not waiting forever
while select([popen.fromchild, popen.childerr], [], []):
readSomething = False
for f in select.result[0]:
while read(f.fileno(), BUFSIZE):
which[id(f)].append(read.result)
readSomething = True
if not readSomething:
break
out, err = ["".join(which[id(f)])
for f in [popen.fromchild, popen.childerr]]
returncode = popen.wait()
if os.WIFEXITED(returncode):
exit = os.WEXITSTATUS(returncode)
else:
exit = returncode or 1 # HACK: ensure non-zero
finally:
try:
popen.fromchild.close()
finally:
popen.childerr.close()
return out or "", err or "", exit
def silentlyRunProcess(cmd,*args):
"""Like `runProcess` but stdout and stderr output is discarded. FIXME: only
works for UNIX!"""
return readProcess(cmd,*args)[2]
def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will not work as expected if `filename` contains
spaces or shell-metacharacters.
If you need more fine-grained control look at ``os.spawn*``.
"""
from os import spawnvp, P_WAIT
return spawnvp(P_WAIT, cmd, (cmd,) + args)
#FIXME; check latest word on this...
def isSeq(obj):
r"""Returns true if obj is a sequence (which does purposefully **not**
include strings, because these are pseudo-sequences that mess
up recursion.)"""
return isinstance(obj, collections.Sequence) and not isinstance(obj, str)
# os.path's splitext is EVIL: it thinks that dotfiles are extensions!
def splitext(p):
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'."""
root, ext = os.path.splitext(p)
# check for dotfiles
if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here???
return (root + ext, "")
else:
return root, ext
#_. LIST MANIPULATION
def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in seq: res[not not func(i)].append(i)
return res
def unzip(seq):
r"""Perform the reverse operation to the builtin `zip` function."""
# XXX should special case for more efficient handling
return list(zip(*seq))
def cmp(a, b):
return (a > b) - (a < b)
def binarySearchPos(seq, item, cmpfunc=cmp):
r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occurence of `item` in `seq`."""
if not seq: return -1
left, right = 0, len(seq) - 1
if cmpfunc(seq[left], item) == 1 and \
cmpfunc(seq[right], item) == -1:
return -1
while left <= right:
halfPoint = (left + right) // 2
comp = cmpfunc(seq[halfPoint], item)
if comp > 0: right = halfPoint - 1
elif comp < 0: left = halfPoint + 1
else: return halfPoint
return -1
__test__['binarySearchPos'] = r"""
>>> binarySearchPos(range(20), 20)
-1
>>> binarySearchPos(range(20), 1)
1
>>> binarySearchPos(range(20), 19)
19
>>> binarySearchPos(range(20), 0)
0
>>> binarySearchPos(range(1,21,2),4)
-1
>>> binarySearchPos(range(0,20,2), 6)
3
>>> binarySearchPos(range(19, -1, -1), 3, lambda x,y:-cmp(x,y))
16
"""
def binarySearchItem(seq, item, cmpfunc=cmp):
r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of item in `seq`."""
pos = binarySearchPos(seq, item, cmpfunc)
if pos == -1: raise KeyError("Item not in seq")
else: return seq[pos]
#XXX could extend this for other sequence types
def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True
"""
if len(l):
steps %= len(l)
if steps:
res = l[steps:]
res.extend(l[:steps])
return res
def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l
# XXX: could wrap that in try: except: for non-hashable types, or provide an
# identity function parameter, but well... this is fast and simple (but wastes
# memory)
def unique(iterable):
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
"""
d = {}
return (d.setdefault(x,x) for x in iterable if x not in d)
__test__['unique'] = r"""
>>> list(unique(range(3))) == range(3)
True
>>> list(unique([1,1,2,2,3,3])) == range(1,4)
True
>>> list(unique([1])) == [1]
True
>>> list(unique([])) == []
True
>>> list(unique(['a','a'])) == ['a']
True
"""
def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if reportMax < 1:
raise ValueError("`reportMax` must be >= 1 and is %r" % reportMax)
for item in iterable:
count = hash[item] = hash.get(item, 0) + 1
if count > 1:
yield item
n += 1
if n >= reportMax:
return
__test__['notUnique'] = r"""
>>> list(notUnique(range(3)))
[]
>>> list(notUnique([1]))
[]
>>> list(notUnique([]))
[]
>>> list(notUnique(['a','a']))
['a']
>>> list(notUnique([1,1,2,2,3,3],2))
[1, 2]
>>> list(notUnique([1,1,2,2,3,3],0))
Traceback (most recent call last):
[...]
ValueError: `reportMax` must be >= 1 and is 0
"""
def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
return res
def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list(weave(iter(('is','psu')), ('there','no', 'censorship')))
['is', 'there', 'psu', 'no']
>>> list(weave(('there','no', 'censorship'), iter(('is','psu'))))
['there', 'is', 'no', 'psu', 'censorship']
"""
iterables = list(map(iter, iterables))
while True:
for it in iterables: yield next(it)
def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
if default is __unique:
return [indexable[i] for i in indices]
else:
res = []
for i in indices:
try:
res.append(indexable[i])
except (IndexError, KeyError):
res.append(default)
return res
__test__['atIndices'] = r'''
>>> atIndices([1,2,3], [1,1,0,4])
Traceback (most recent call last):
[...]
IndexError: list index out of range
>>> atIndices({1:2,3:4}, [1,1,0,4])
Traceback (most recent call last):
[...]
KeyError: 0
>>> atIndices({1:2,3:4}, [1,1,0,4], 'default')
[2, 2, 'default', 'default']
'''
#XXX: should those have reduce like optional end-argument?
#FIXME should s defaul to n? (1 is less typing/better than len(somearg(foo)); )
def window(iterable, n=2, s=1):
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(window(range(6),3, 2))
[(0, 1, 2), (2, 3, 4)]
>>> list(window(range(5),3,2)) == list(window(range(6),3,2))
True
"""
assert n >= s
last = []
for elt in iterable:
last.append(elt)
if len(last) == n: yield tuple(last); last=last[s:]
#FIXME
xwindow = window
# FIXME rename to block?
def group(iterable, n=2, pad=__unique):
r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John surname: Ford
>>>
>>> # both contain the same number of pairs
>>> list(group(range(9))) == list(group(range(8)))
True
>>> # with n=3
>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(group(range(10), 3, pad=0))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0)]
"""
assert n>0 # ensure it doesn't loop forever
if pad is not __unique: it = chain(iterable, (pad,)*(n-1))
else: it = iter(iterable)
perTuple = list(range(n))
while True:
yield tuple([next(it) for i in perTuple])
def iterate(f, n=None, last=__unique):
"""
>>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64]
"""
if n is not None:
def funciter(start):
for i in range(n): yield start; start = f(start)
else:
def funciter(start):
while True:
yield start
last = f(start)
if last == start: return
last, start = start, last
return funciter
def dropwhilenot(func, iterable):
"""
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
"""
iterable = iter(iterable)
for x in iterable:
if func(x): break
else: return
yield x
for x in iterable:
yield x
def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = list(range(n))
for item in iterable:
for i in times: yield item
def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
"""
iterable = iter(iterable)
now = 0
for to in indices:
try:
res = []
for i in range(now, to): res.append(next(iterable))
except StopIteration: yield res; return
yield res
now = to
res = list(iterable)
if res: yield res
__test__['splitAt'] = r"""
>>> [l for l in splitAt(range(10), [1,5])]
[[0], [1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
>>> [l for l in splitAt(range(10), [2,5,9])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8], [9]]
>>> [l for l in splitAt(range(10), [2,5,11])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
"""
#_. HASH MANIPULATION
# XXX should we use copy or start with empty dict? former is more generic
# (should work for other dict types, too)
def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res
def invertDict(d, allowManyToOne=False):
r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversion.
Examples:
>>> invertDict({1: 2, 3: 4}) == {2: 1, 4: 3}
True
>>> invertDict({1: 2, 3: 2})
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: d can't be inverted!
>>> invertDict({1: 2, 3: 2}, allowManyToOne=True).keys()
[2]
"""
res = dict(list(zip(iter(list(d.values())), iter(list(d.keys())))))
if not allowManyToOne and len(res) != len(d):
raise ValueError("d can't be inverted!")
return res
#_. LISP LIKES
#AARGH strings are EVIL...
def iflatten(seq, isSeq=isSeq):
r"""Like `flatten` but lazy."""
for elt in seq:
if isSeq(elt):
for x in iflatten(elt, isSeq):
yield x
else:
yield elt
__test__['iflatten'] = r"""
>>> type(iflatten([]))
<type 'generator'>
>>> iflatten([]).next()
Traceback (most recent call last):
File "<console>", line 1, in ?
StopIteration
>>> (a,b,c) = iflatten([1,["2", ([3],)]])
>>> (a,b,c) == (1, '2', 3)
True
"""
def flatten(seq, isSeq=isSeq):
r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
**never** test positive for strings, because they are no real
sequences and thus cause infinite recursion.*
Examples:
>>> flatten([1,[2,3,(4,[5,6]),7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> # flaten only lists
>>> flatten([1,[2,3,(4,[5,6]),7,8]], isSeq=lambda x:isinstance(x, list))
[1, 2, 3, (4, [5, 6]), 7, 8]
>>> flatten([1,2])
[1, 2]
>>> flatten([])
[]
>>> flatten('123')
['1', '2', '3']
"""
return [a for elt in seq
for a in (isSeq(elt) and flatten(elt, isSeq) or
[elt])]
def countIf(predicate, iterable):
r"""Count all the elements of for which `predicate` returns true."""
return sum(1 for x in iterable if predicate(x))
__test__['countIf'] = r"""
>>> countIf(bool, range(10))
9
>>> countIf(bool, range(-1))
0
"""
def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1
def union(seq1=(), *seqs):
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> union([1,2,3], iter([0,1,1,1]))
[0, 1, 2, 3]