-
Notifications
You must be signed in to change notification settings - Fork 8
/
setup.py
2426 lines (2383 loc) · 118 KB
/
setup.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0x6935ef16
# Compiled with Coconut version 3.0.0-a_dev36
# Coconut Header: -------------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
import sys as _coconut_sys
_coconut_cached__coconut__ = _coconut_sys.modules.get(str('_coconut_cached__coconut__'), _coconut_sys.modules.get(str('__coconut__')))
if _coconut_sys.version_info < (3,):
from __builtin__ import chr, dict, hex, input, int, map, object, oct, open, print, range, str, super, zip, filter, reversed, enumerate, raw_input, xrange, repr, long
py_chr, py_dict, py_hex, py_input, py_int, py_map, py_object, py_oct, py_open, py_print, py_range, py_str, py_super, py_zip, py_filter, py_reversed, py_enumerate, py_raw_input, py_xrange, py_repr = chr, dict, hex, input, int, map, object, oct, open, print, range, str, super, zip, filter, reversed, enumerate, raw_input, xrange, repr
_coconut_py_raw_input, _coconut_py_xrange, _coconut_py_int, _coconut_py_long, _coconut_py_print, _coconut_py_str, _coconut_py_super, _coconut_py_unicode, _coconut_py_repr, _coconut_py_dict = raw_input, xrange, int, long, print, str, super, unicode, repr, dict
from functools import wraps as _coconut_wraps
from collections import Sequence as _coconut_Sequence
from future_builtins import *
chr, str = unichr, unicode
from io import open
class object(object):
__slots__ = ()
def __ne__(self, other):
eq = self == other
return _coconut.NotImplemented if eq is _coconut.NotImplemented else not eq
def __nonzero__(self):
if _coconut.hasattr(self, "__bool__"):
got = self.__bool__()
if not _coconut.isinstance(got, _coconut.bool):
raise _coconut.TypeError("__bool__ should return bool, returned " + _coconut.type(got).__name__)
return got
return True
class int(_coconut_py_int):
__slots__ = ()
__doc__ = getattr(_coconut_py_int, "__doc__", "<see help(py_int)>")
class __metaclass__(type):
def __instancecheck__(cls, inst):
return _coconut.isinstance(inst, (_coconut_py_int, _coconut_py_long))
def __subclasscheck__(cls, subcls):
return _coconut.issubclass(subcls, (_coconut_py_int, _coconut_py_long))
class range(object):
__slots__ = ("_xrange",)
__doc__ = getattr(_coconut_py_xrange, "__doc__", "<see help(py_xrange)>")
def __init__(self, *args):
self._xrange = _coconut_py_xrange(*args)
def __iter__(self):
return _coconut.iter(self._xrange)
def __reversed__(self):
return _coconut.reversed(self._xrange)
def __len__(self):
return _coconut.len(self._xrange)
def __bool__(self):
return _coconut.bool(self._xrange)
def __contains__(self, elem):
return elem in self._xrange
def __getitem__(self, index):
if _coconut.isinstance(index, _coconut.slice):
args = _coconut.slice(*self._args)
start, stop, step = (args.start if args.start is not None else 0), args.stop, (args.step if args.step is not None else 1)
if index.start is None:
new_start = start if index.step is None or index.step >= 0 else stop - step
elif index.start >= 0:
new_start = start + step * index.start
if (step >= 0 and new_start >= stop) or (step < 0 and new_start <= stop):
new_start = stop
else:
new_start = stop + step * index.start
if (step >= 0 and new_start <= start) or (step < 0 and new_start >= start):
new_start = start
if index.stop is None:
new_stop = stop if index.step is None or index.step >= 0 else start - step
elif index.stop >= 0:
new_stop = start + step * index.stop
if (step >= 0 and new_stop >= stop) or (step < 0 and new_stop <= stop):
new_stop = stop
else:
new_stop = stop + step * index.stop
if (step >= 0 and new_stop <= start) or (step < 0 and new_stop >= start):
new_stop = start
new_step = step if index.step is None else step * index.step
return self.__class__(new_start, new_stop, new_step)
else:
return self._xrange[index]
def count(self, elem):
"""Count the number of times elem appears in the range."""
return _coconut_py_int(elem in self._xrange)
def index(self, elem):
"""Find the index of elem in the range."""
if elem not in self._xrange: raise _coconut.ValueError(_coconut.repr(elem) + " is not in range")
start, _, step = self._xrange.__reduce_ex__(2)[1]
return (elem - start) // step
def __repr__(self):
return _coconut.repr(self._xrange)[1:]
@property
def _args(self):
return self._xrange.__reduce__()[1]
def __reduce_ex__(self, protocol):
return (self.__class__, self._xrange.__reduce_ex__(protocol)[1])
def __reduce__(self):
return self.__reduce_ex__(_coconut.pickle.DEFAULT_PROTOCOL)
def __hash__(self):
return _coconut.hash(self._args)
def __copy__(self):
return self.__class__(*self._args)
def __eq__(self, other):
return self.__class__ is other.__class__ and self._args == other._args
_coconut_Sequence.register(range)
@_coconut_wraps(_coconut_py_print)
def print(*args, **kwargs):
file = kwargs.get("file", _coconut_sys.stdout)
if "flush" in kwargs:
flush = kwargs["flush"]
del kwargs["flush"]
else:
flush = False
if _coconut.getattr(file, "encoding", None) is not None:
_coconut_py_print(*(_coconut_py_unicode(x).encode(file.encoding) for x in args), **kwargs)
else:
_coconut_py_print(*args, **kwargs)
if flush:
file.flush()
@_coconut_wraps(_coconut_py_raw_input)
def input(*args, **kwargs):
if _coconut.getattr(_coconut_sys.stdout, "encoding", None) is not None:
return _coconut_py_raw_input(*args, **kwargs).decode(_coconut_sys.stdout.encoding)
return _coconut_py_raw_input(*args, **kwargs).decode()
@_coconut_wraps(_coconut_py_repr)
def repr(obj):
import __builtin__
try:
__builtin__.repr = _coconut_repr
if isinstance(obj, _coconut_py_unicode):
return _coconut_py_unicode(_coconut_py_repr(obj)[1:])
if isinstance(obj, _coconut_py_str):
return "b" + _coconut_py_unicode(_coconut_py_repr(obj))
return _coconut_py_unicode(_coconut_py_repr(obj))
finally:
__builtin__.repr = _coconut_py_repr
ascii = _coconut_repr = repr
def raw_input(*args):
"""Coconut uses Python 3 'input' instead of Python 2 'raw_input'."""
raise _coconut.NameError("Coconut uses Python 3 'input' instead of Python 2 'raw_input'")
def xrange(*args):
"""Coconut uses Python 3 'range' instead of Python 2 'xrange'."""
raise _coconut.NameError("Coconut uses Python 3 'range' instead of Python 2 'xrange'")
def _coconut_exec(obj, globals=None, locals=None):
"""Execute the given source in the context of globals and locals."""
if locals is None:
locals = _coconut_sys._getframe(1).f_locals if globals is None else globals
if globals is None:
globals = _coconut_sys._getframe(1).f_globals
exec(obj, globals, locals)
def _coconut_default_breakpointhook(*args, **kwargs):
hookname = _coconut.os.getenv("PYTHONBREAKPOINT")
if hookname != "0":
if not hookname:
hookname = "pdb.set_trace"
modname, dot, funcname = hookname.rpartition(".")
if not dot:
modname = "builtins" if _coconut_sys.version_info >= (3,) else "__builtin__"
if _coconut_sys.version_info >= (2, 7):
import importlib
module = importlib.import_module(modname)
else:
import imp
module = imp.load_module(modname, *imp.find_module(modname))
hook = _coconut.getattr(module, funcname)
return hook(*args, **kwargs)
if not hasattr(_coconut_sys, "__breakpointhook__"):
_coconut_sys.__breakpointhook__ = _coconut_default_breakpointhook
def breakpoint(*args, **kwargs):
return _coconut.getattr(_coconut_sys, "breakpointhook", _coconut_default_breakpointhook)(*args, **kwargs)
if _coconut_sys.version_info < (2, 7):
import functools as _coconut_functools, copy_reg as _coconut_copy_reg
def _coconut_new_partial(func, args, keywords):
return _coconut_functools.partial(func, *(args if args is not None else ()), **(keywords if keywords is not None else {}))
_coconut_copy_reg.constructor(_coconut_new_partial)
def _coconut_reduce_partial(self):
return (_coconut_new_partial, (self.func, self.args, self.keywords))
_coconut_copy_reg.pickle(_coconut_functools.partial, _coconut_reduce_partial)
from collections import OrderedDict as _coconut_OrderedDict
class _coconut_dict_base(_coconut_OrderedDict):
__slots__ = ()
__doc__ = getattr(_coconut_OrderedDict, "__doc__", "<see help(py_dict)>")
__eq__ = _coconut_py_dict.__eq__
def __repr__(self):
return "{" + ", ".join("{k!r}: {v!r}".format(k=k, v=v) for k, v in self.items()) + "}"
def __or__(self, other):
out = self.copy()
out.update(other)
return out
def __ror__(self, other):
out = self.__class__(other)
out.update(self)
return out
def __ior__(self, other):
self.update(other)
return self
class _coconut_dict_meta(type):
def __instancecheck__(cls, inst):
return _coconut.isinstance(inst, _coconut_py_dict)
def __subclasscheck__(cls, subcls):
return _coconut.issubclass(subcls, _coconut_py_dict)
dict = _coconut_dict_meta(py_str("dict"), _coconut_dict_base.__bases__, _coconut_dict_base.__dict__.copy())
dict.keys = _coconut_OrderedDict.viewkeys
dict.values = _coconut_OrderedDict.viewvalues
dict.items = _coconut_OrderedDict.viewitems
else:
from builtins import chr, dict, hex, input, int, map, object, oct, open, print, range, str, super, zip, filter, reversed, enumerate, repr
py_chr, py_dict, py_hex, py_input, py_int, py_map, py_object, py_oct, py_open, py_print, py_range, py_str, py_super, py_zip, py_filter, py_reversed, py_enumerate, py_repr = chr, dict, hex, input, int, map, object, oct, open, print, range, str, super, zip, filter, reversed, enumerate, repr
_coconut_py_str, _coconut_py_super, _coconut_py_dict = str, super, dict
from functools import wraps as _coconut_wraps
exec("_coconut_exec = exec")
if _coconut_sys.version_info < (3, 7):
def _coconut_default_breakpointhook(*args, **kwargs):
hookname = _coconut.os.getenv("PYTHONBREAKPOINT")
if hookname != "0":
if not hookname:
hookname = "pdb.set_trace"
modname, dot, funcname = hookname.rpartition(".")
if not dot:
modname = "builtins" if _coconut_sys.version_info >= (3,) else "__builtin__"
if _coconut_sys.version_info >= (2, 7):
import importlib
module = importlib.import_module(modname)
else:
import imp
module = imp.load_module(modname, *imp.find_module(modname))
hook = _coconut.getattr(module, funcname)
return hook(*args, **kwargs)
if not hasattr(_coconut_sys, "__breakpointhook__"):
_coconut_sys.__breakpointhook__ = _coconut_default_breakpointhook
def breakpoint(*args, **kwargs):
return _coconut.getattr(_coconut_sys, "breakpointhook", _coconut_default_breakpointhook)(*args, **kwargs)
else:
py_breakpoint = breakpoint
if _coconut_sys.version_info < (3, 7):
from collections import OrderedDict as _coconut_OrderedDict
class _coconut_dict_base(_coconut_OrderedDict):
__slots__ = ()
__doc__ = getattr(_coconut_OrderedDict, "__doc__", "<see help(py_dict)>")
__eq__ = _coconut_py_dict.__eq__
def __repr__(self):
return "{" + ", ".join("{k!r}: {v!r}".format(k=k, v=v) for k, v in self.items()) + "}"
def __or__(self, other):
out = self.copy()
out.update(other)
return out
def __ror__(self, other):
out = self.__class__(other)
out.update(self)
return out
def __ior__(self, other):
self.update(other)
return self
class _coconut_dict_meta(type):
def __instancecheck__(cls, inst):
return _coconut.isinstance(inst, _coconut_py_dict)
def __subclasscheck__(cls, subcls):
return _coconut.issubclass(subcls, _coconut_py_dict)
dict = _coconut_dict_meta(py_str("dict"), _coconut_dict_base.__bases__, _coconut_dict_base.__dict__.copy())
elif _coconut_sys.version_info < (3, 9):
class _coconut_dict_base(_coconut_py_dict):
__slots__ = ()
__doc__ = getattr(_coconut_py_dict, "__doc__", "<see help(py_dict)>")
def __or__(self, other):
out = self.copy()
out.update(other)
return out
def __ror__(self, other):
out = self.__class__(other)
out.update(self)
return out
def __ior__(self, other):
self.update(other)
return self
class _coconut_dict_meta(type):
def __instancecheck__(cls, inst):
return _coconut.isinstance(inst, _coconut_py_dict)
def __subclasscheck__(cls, subcls):
return _coconut.issubclass(subcls, _coconut_py_dict)
dict = _coconut_dict_meta(py_str("dict"), _coconut_dict_base.__bases__, _coconut_dict_base.__dict__.copy())
@_coconut_wraps(_coconut_py_super)
def _coconut_super(type=None, object_or_type=None):
if type is None:
if object_or_type is not None:
raise _coconut.TypeError("invalid use of super()")
frame = _coconut_sys._getframe(1)
try:
cls = frame.f_locals["__class__"]
except _coconut.AttributeError:
raise _coconut.RuntimeError("super(): __class__ cell not found")
self = frame.f_locals[frame.f_code.co_varnames[0]]
return _coconut_py_super(cls, self)
return _coconut_py_super(type, object_or_type)
super = _coconut_super
class _coconut(object):
import collections, copy, functools, types, itertools, operator, threading, os, warnings, contextlib, traceback, weakref, multiprocessing
from multiprocessing import dummy as multiprocessing_dummy
if _coconut_sys.version_info < (3, 2):
try:
from backports.functools_lru_cache import lru_cache
functools.lru_cache = lru_cache
except ImportError:
class you_need_to_install_backports_functools_lru_cache(object):
__slots__ = ()
functools.lru_cache = you_need_to_install_backports_functools_lru_cache()
if _coconut_sys.version_info < (3,):
import copy_reg as copyreg
else:
import copyreg
if _coconut_sys.version_info < (3, 4):
try:
import trollius as asyncio
except ImportError:
class you_need_to_install_trollius(object):
__slots__ = ()
asyncio = you_need_to_install_trollius()
else:
import asyncio
if _coconut_sys.version_info < (3,):
import cPickle as pickle
else:
import pickle
OrderedDict = collections.OrderedDict if _coconut_sys.version_info >= (2, 7) else dict
if _coconut_sys.version_info < (3, 3):
abc = collections
else:
import collections.abc as abc
if _coconut_sys.version_info < (3, 5):
class typing_mock(object):
"""The typing module is not available at runtime in Python 3.4 or earlier;
try hiding your typedefs behind an 'if TYPE_CHECKING:' block."""
TYPE_CHECKING = False
Any = Ellipsis
def cast(self, t, x):
"""typing.cast[T](t: Type[T], x: Any) -> T = x"""
return x
def __getattr__(self, name):
raise _coconut.ImportError("the typing module is not available at runtime in Python 3.4 or earlier; try hiding your typedefs behind an 'if TYPE_CHECKING:' block")
def TypeVar(name, *args, **kwargs):
"""Runtime mock of typing.TypeVar for Python 3.4 and earlier."""
return name
class Generic_mock(object):
"""Runtime mock of typing.Generic for Python 3.4 and earlier."""
__slots__ = ()
def __getitem__(self, vars):
return _coconut.object
Generic = Generic_mock()
typing = typing_mock()
else:
import typing
if _coconut_sys.version_info < (3, 6):
def NamedTuple(name, fields):
return _coconut.collections.namedtuple(name, [x for x, t in fields])
typing.NamedTuple = NamedTuple
NamedTuple = staticmethod(NamedTuple)
if _coconut_sys.version_info < (3, 8):
try:
from typing_extensions import Protocol
except ImportError:
class YouNeedToInstallTypingExtensions(object):
__slots__ = ()
Protocol = YouNeedToInstallTypingExtensions
typing.Protocol = Protocol
if _coconut_sys.version_info < (3, 10):
try:
from typing_extensions import TypeAlias, ParamSpec, Concatenate
except ImportError:
class you_need_to_install_typing_extensions(object):
__slots__ = ()
TypeAlias = ParamSpec = Concatenate = you_need_to_install_typing_extensions()
typing.TypeAlias = TypeAlias
typing.ParamSpec = ParamSpec
typing.Concatenate = Concatenate
if _coconut_sys.version_info < (3, 11):
try:
from typing_extensions import TypeVarTuple, Unpack
except ImportError:
class you_need_to_install_typing_extensions(object):
__slots__ = ()
TypeVarTuple = Unpack = you_need_to_install_typing_extensions()
typing.TypeVarTuple = TypeVarTuple
typing.Unpack = Unpack
zip_longest = itertools.zip_longest if _coconut_sys.version_info >= (3,) else itertools.izip_longest
try:
import numpy
except ImportError:
class you_need_to_install_numpy(object):
__slots__ = ()
numpy = you_need_to_install_numpy()
else:
abc.Sequence.register(numpy.ndarray)
numpy_modules = ('numpy', 'pandas', 'torch', 'jaxlib.xla_extension')
jax_numpy_modules = ('jaxlib.xla_extension',)
tee_type = type(itertools.tee((), 1)[0])
reiterables = abc.Sequence, abc.Mapping, abc.Set
abc.Sequence.register(collections.deque)
Ellipsis, NotImplemented, NotImplementedError, Exception, AttributeError, ImportError, IndexError, KeyError, NameError, TypeError, ValueError, StopIteration, RuntimeError, all, any, bool, bytes, callable, classmethod, complex, dict, enumerate, filter, float, frozenset, getattr, hasattr, hash, id, int, isinstance, issubclass, iter, len, list, locals, globals, map, min, max, next, object, property, range, reversed, set, setattr, slice, str, sum, super, tuple, type, vars, zip, repr, print, bytearray = Ellipsis, NotImplemented, NotImplementedError, Exception, AttributeError, ImportError, IndexError, KeyError, NameError, TypeError, ValueError, StopIteration, RuntimeError, all, any, bool, bytes, callable, classmethod, complex, dict, enumerate, filter, float, frozenset, getattr, hasattr, hash, id, int, isinstance, issubclass, iter, len, list, locals, globals, map, min, max, next, object, property, range, reversed, set, setattr, slice, str, sum, staticmethod(super), tuple, type, vars, zip, staticmethod(repr), staticmethod(print), bytearray
def _coconut_handle_cls_kwargs(**kwargs):
"""Some code taken from six under the terms of its MIT license."""
metaclass = kwargs.pop("metaclass", None)
if kwargs and metaclass is None:
raise _coconut.TypeError("unexpected keyword argument(s) in class definition: %r" % (kwargs,))
def coconut_handle_cls_kwargs_wrapper(cls):
if metaclass is None:
return cls
orig_vars = cls.__dict__.copy()
slots = orig_vars.get("__slots__")
if slots is not None:
if _coconut.isinstance(slots, _coconut.str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop("__dict__", None)
orig_vars.pop("__weakref__", None)
if _coconut.hasattr(cls, "__qualname__"):
orig_vars["__qualname__"] = cls.__qualname__
return metaclass(cls.__name__, cls.__bases__, orig_vars, **kwargs)
return coconut_handle_cls_kwargs_wrapper
def _coconut_handle_cls_stargs(*args):
temp_names = ["_coconut_base_cls_%s" % (i,) for i in _coconut.range(_coconut.len(args))]
ns = _coconut_py_dict(_coconut.zip(temp_names, args))
_coconut_exec("class _coconut_cls_stargs_base(" + ", ".join(temp_names) + "): pass", ns)
return ns["_coconut_cls_stargs_base"]
class _coconut_baseclass(object):
__slots__ = ("__weakref__",)
def __reduce_ex__(self, _):
return self.__reduce__()
def __eq__(self, other):
return self.__class__ is other.__class__ and self.__reduce__() == other.__reduce__()
def __hash__(self):
return _coconut.hash(self.__reduce__())
def __setstate__(self, setvars):
for k, v in setvars.items():
_coconut.setattr(self, k, v)
class _coconut_Sentinel(_coconut_baseclass):
__slots__ = ()
def __reduce__(self):
return (self.__class__, ())
_coconut_sentinel = _coconut_Sentinel()
class MatchError(_coconut_baseclass, Exception):
"""Pattern-matching error. Has attributes .pattern, .value, and .message."""
max_val_repr_len = 500
def __init__(self, pattern=None, value=None):
self.pattern = pattern
self.value = value
self._message = None
@property
def message(self):
if self._message is None:
val_repr = _coconut.repr(self.value)
self._message = "pattern-matching failed for %s in %s" % (_coconut.repr(self.pattern), val_repr if _coconut.len(val_repr) <= self.max_val_repr_len else val_repr[:self.max_val_repr_len] + "...")
Exception.__init__(self, self._message)
return self._message
def __repr__(self):
self.message
return Exception.__repr__(self)
def __str__(self):
self.message
return Exception.__str__(self)
def __unicode__(self):
self.message
return Exception.__unicode__(self)
def __reduce__(self):
return (self.__class__, (self.pattern, self.value), {"_message": self._message})
def __setstate__(self, state):
_coconut_baseclass.__setstate__(self, state)
if self._message is not None:
Exception.__init__(self, self._message)
_coconut_cached_MatchError = None if _coconut_cached__coconut__ is None else getattr(_coconut_cached__coconut__, "MatchError", None)
if _coconut_cached_MatchError is not None:
if _coconut_sys.version_info >= (3,):
for _coconut_varname in dir(MatchError):
try:
setattr(_coconut_cached_MatchError, _coconut_varname, getattr(MatchError, _coconut_varname))
except (AttributeError, TypeError):
pass
MatchError = _coconut_cached_MatchError
class _coconut_tail_call(_coconut_baseclass):
__slots__ = ("func", "args", "kwargs")
def __init__(self, _coconut_func, *args, **kwargs):
self.func = _coconut_func
self.args = args
self.kwargs = kwargs
def __reduce__(self):
return (self.__class__, (self.func, self.args, self.kwargs))
_coconut_tco_func_dict = _coconut.dict()
def _coconut_tco(func):
@_coconut.functools.wraps(func)
def tail_call_optimized_func(*args, **kwargs):
call_func = func
while True:
if _coconut.isinstance(call_func, _coconut_base_pattern_func):
call_func = call_func._coconut_tco_func
elif _coconut.isinstance(call_func, _coconut.types.MethodType):
wkref = _coconut_tco_func_dict.get(_coconut.id(call_func.__func__))
wkref_func = None if wkref is None else wkref()
if wkref_func is call_func.__func__:
if call_func.__self__ is None:
call_func = call_func._coconut_tco_func
else:
call_func = _coconut.functools.partial(call_func._coconut_tco_func, call_func.__self__)
else:
wkref = _coconut_tco_func_dict.get(_coconut.id(call_func))
wkref_func = None if wkref is None else wkref()
if wkref_func is call_func:
call_func = call_func._coconut_tco_func
result = call_func(*args, **kwargs) # use 'coconut --no-tco' to clean up your traceback
if not isinstance(result, _coconut_tail_call):
return result
call_func, args, kwargs = result.func, result.args, result.kwargs
tail_call_optimized_func._coconut_tco_func = func
tail_call_optimized_func.__module__ = _coconut.getattr(func, "__module__", None)
tail_call_optimized_func.__name__ = _coconut.getattr(func, "__name__", None)
tail_call_optimized_func.__qualname__ = _coconut.getattr(func, "__qualname__", None)
_coconut_tco_func_dict[_coconut.id(tail_call_optimized_func)] = _coconut.weakref.ref(tail_call_optimized_func)
return tail_call_optimized_func
@_coconut.functools.wraps(_coconut.itertools.tee)
def tee(iterable, n=2):
if n < 0:
raise ValueError("tee: n cannot be negative")
elif n == 0:
return ()
elif n == 1:
return (iterable,)
elif _coconut.isinstance(iterable, _coconut.reiterables):
return (iterable,) * n
else:
if _coconut.getattr(iterable, "__getitem__", None) is not None or _coconut.isinstance(iterable, (_coconut.tee_type, _coconut.abc.Sized, _coconut.abc.Container)):
existing_copies = [iterable]
while _coconut.len(existing_copies) < n:
try:
copy = _coconut.copy.copy(iterable)
except _coconut.TypeError:
break
else:
existing_copies.append(copy)
else:
return _coconut.tuple(existing_copies)
return _coconut.itertools.tee(iterable, n)
class _coconut_has_iter(_coconut_baseclass):
__slots__ = ("lock", "iter")
def __new__(cls, iterable):
self = _coconut.object.__new__(cls)
self.lock = _coconut.threading.Lock()
self.iter = iterable
return self
def get_new_iter(self):
"""Tee the underlying iterator."""
with self.lock:
self.iter = _coconut_reiterable(self.iter)
return self.iter
def __fmap__(self, func):
return _coconut_map(func, self)
class reiterable(_coconut_has_iter):
"""Allow an iterator to be iterated over multiple times with the same results."""
__slots__ = ()
def __new__(cls, iterable):
if _coconut.isinstance(iterable, _coconut.reiterables):
return iterable
return _coconut_has_iter.__new__(cls, iterable)
def get_new_iter(self):
"""Tee the underlying iterator."""
with self.lock:
self.iter, new_iter = _coconut_tee(self.iter)
return new_iter
def __iter__(self):
return _coconut.iter(self.get_new_iter())
def __repr__(self):
return "reiterable(%s)" % (_coconut.repr(self.get_new_iter()),)
def __reduce__(self):
return (self.__class__, (self.iter,))
def __copy__(self):
return self.__class__(self.get_new_iter())
def __getitem__(self, index):
return _coconut_iter_getitem(self.get_new_iter(), index)
def __reversed__(self):
return _coconut_reversed(self.get_new_iter())
def __len__(self):
if not _coconut.isinstance(self.iter, _coconut.abc.Sized):
return _coconut.NotImplemented
return _coconut.len(self.get_new_iter())
def __contains__(self, elem):
return elem in self.get_new_iter()
def count(self, elem):
"""Count the number of times elem appears in the iterable."""
return self.get_new_iter().count(elem)
def index(self, elem):
"""Find the index of elem in the iterable."""
return self.get_new_iter().index(elem)
_coconut.reiterables = (reiterable,) + _coconut.reiterables
def _coconut_iter_getitem_special_case(iterable, start, stop, step):
iterable = _coconut.itertools.islice(iterable, start, None)
cache = _coconut.collections.deque(_coconut.itertools.islice(iterable, -stop), maxlen=-stop)
for index, item in _coconut.enumerate(iterable):
cached_item = cache.popleft()
if index % step == 0:
yield cached_item
cache.append(item)
def _coconut_iter_getitem(iterable, index):
"""Iterator slicing works just like sequence slicing, including support for negative indices and slices, and support for `slice` objects in the same way as can be done with normal slicing.
Coconut's iterator slicing is very similar to Python's `itertools.islice`, but unlike `itertools.islice`, Coconut's iterator slicing supports negative indices, and will preferentially call an object's `__iter_getitem__` (Coconut-specific magic method, preferred) or `__getitem__` (general Python magic method), if they exist. Coconut's iterator slicing is also optimized to work well with all of Coconut's built-in objects, only computing the elements of each that are actually necessary to extract the desired slice.
Some code taken from more_itertools under the terms of its MIT license.
"""
obj_iter_getitem = _coconut.getattr(iterable, "__iter_getitem__", None)
if obj_iter_getitem is None:
obj_iter_getitem = _coconut.getattr(iterable, "__getitem__", None)
if obj_iter_getitem is not None:
try:
result = obj_iter_getitem(index)
except _coconut.NotImplementedError:
pass
else:
if result is not _coconut.NotImplemented:
return result
if not _coconut.isinstance(index, _coconut.slice):
index = _coconut.operator.index(index)
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
result = _coconut.next(_coconut.itertools.islice(iterable, index, index + 1), _coconut_sentinel)
if result is _coconut_sentinel:
raise _coconut.IndexError(".$[] index out of range")
return result
start = _coconut.operator.index(index.start) if index.start is not None else None
stop = _coconut.operator.index(index.stop) if index.stop is not None else None
step = _coconut.operator.index(index.step) if index.step is not None else 1
if step == 0:
raise _coconut.ValueError("slice step cannot be zero")
if start is None and stop is None and step == -1:
obj_reversed = _coconut.getattr(iterable, "__reversed__", None)
if obj_reversed is not None:
try:
result = obj_reversed()
except _coconut.NotImplementedError:
pass
else:
if result is not _coconut.NotImplemented:
return result
if step >= 0:
start = 0 if start is None else start
if start < 0:
cache = _coconut.collections.deque(_coconut.enumerate(iterable, 1), maxlen=-start)
len_iter = cache[-1][0] if cache else 0
i = _coconut.max(len_iter + start, 0)
if stop is None:
j = len_iter
elif stop >= 0:
j = _coconut.min(stop, len_iter)
else:
j = _coconut.max(len_iter + stop, 0)
n = j - i
if n <= 0:
return ()
if n < -start or step != 1:
cache = _coconut.itertools.islice(cache, 0, n, step)
return _coconut_map(_coconut.operator.itemgetter(1), cache)
elif stop is None or stop >= 0:
return _coconut.itertools.islice(iterable, start, stop, step)
else:
return _coconut_iter_getitem_special_case(iterable, start, stop, step)
else:
start = -1 if start is None else start
if stop is not None and stop < 0:
n = -stop - 1
cache = _coconut.collections.deque(_coconut.enumerate(iterable, 1), maxlen=n)
len_iter = cache[-1][0] if cache else 0
if start < 0:
i, j = start, stop
else:
i, j = _coconut.min(start - len_iter, -1), None
return _coconut_map(_coconut.operator.itemgetter(1), _coconut.tuple(cache)[i:j:step])
else:
if stop is not None:
m = stop + 1
iterable = _coconut.itertools.islice(iterable, m, None)
if start < 0:
i = start
n = None
elif stop is None:
i = None
n = start + 1
else:
i = None
n = start - stop
if n is not None:
if n <= 0:
return ()
iterable = _coconut.itertools.islice(iterable, 0, n)
return _coconut.tuple(iterable)[i::step]
class _coconut_base_compose(_coconut_baseclass):
__slots__ = ("func", "func_infos")
def __init__(self, func, *func_infos):
self.func = func
self.func_infos = []
for f, stars, none_aware in func_infos:
if _coconut.isinstance(f, _coconut_base_compose):
self.func_infos.append((f.func, stars, none_aware))
self.func_infos += f.func_infos
else:
self.func_infos.append((f, stars, none_aware))
self.func_infos = _coconut.tuple(self.func_infos)
def __call__(self, *args, **kwargs):
arg = self.func(*args, **kwargs)
for f, stars, none_aware in self.func_infos:
if none_aware and arg is None:
return arg
if stars == 0:
arg = f(arg)
elif stars == 1:
arg = f(*arg)
elif stars == 2:
arg = f(**arg)
else:
raise _coconut.RuntimeError("invalid internal stars value " + _coconut.repr(stars) + " in " + _coconut.repr(self) + " (you should report this at https://github.com/evhub/coconut/issues/new)")
return arg
def __repr__(self):
return _coconut.repr(self.func) + " " + " ".join(".." + "?"*none_aware + "*"*stars + "> " + _coconut.repr(f) for f, stars, none_aware in self.func_infos)
def __reduce__(self):
return (self.__class__, (self.func,) + self.func_infos)
def __get__(self, obj, objtype=None):
if obj is None:
return self
if _coconut_sys.version_info < (3,):
return _coconut.types.MethodType(self, obj, objtype)
else:
return _coconut.types.MethodType(self, obj)
def _coconut_forward_compose(func, *funcs):
"""Forward composition operator (..>).
(..>)(f, g) is effectively equivalent to (*args, **kwargs) -> g(f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 0, False) for f in funcs))
def _coconut_back_compose(*funcs):
"""Backward composition operator (<..).
(<..)(f, g) is effectively equivalent to (*args, **kwargs) -> f(g(*args, **kwargs))."""
return _coconut_forward_compose(*_coconut.reversed(funcs))
def _coconut_forward_star_compose(func, *funcs):
"""Forward star composition operator (..*>).
(..*>)(f, g) is effectively equivalent to (*args, **kwargs) -> g(*f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 1, False) for f in funcs))
def _coconut_back_star_compose(*funcs):
"""Backward star composition operator (<*..).
(<*..)(f, g) is effectively equivalent to (*args, **kwargs) -> f(*g(*args, **kwargs))."""
return _coconut_forward_star_compose(*_coconut.reversed(funcs))
def _coconut_forward_dubstar_compose(func, *funcs):
"""Forward double star composition operator (..**>).
(..**>)(f, g) is effectively equivalent to (*args, **kwargs) -> g(**f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 2, False) for f in funcs))
def _coconut_back_dubstar_compose(*funcs):
"""Backward double star composition operator (<**..).
(<**..)(f, g) is effectively equivalent to (*args, **kwargs) -> f(**g(*args, **kwargs))."""
return _coconut_forward_dubstar_compose(*_coconut.reversed(funcs))
def _coconut_forward_none_compose(func, *funcs):
"""Forward none-aware composition operator (..?>).
(..?>)(f, g) is effectively equivalent to (*args, **kwargs) -> g?(f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 0, True) for f in funcs))
def _coconut_back_none_compose(*funcs):
"""Backward none-aware composition operator (<..?).
(<..?)(f, g) is effectively equivalent to (*args, **kwargs) -> f?(g(*args, **kwargs))."""
return _coconut_forward_none_compose(*_coconut.reversed(funcs))
def _coconut_forward_none_star_compose(func, *funcs):
"""Forward none-aware star composition operator (..?*>).
(..?*>)(f, g) is effectively equivalent to (*args, **kwargs) -> g?(*f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 1, True) for f in funcs))
def _coconut_back_none_star_compose(*funcs):
"""Backward none-aware star composition operator (<*?..).
(<*?..)(f, g) is effectively equivalent to (*args, **kwargs) -> f?(*g(*args, **kwargs))."""
return _coconut_forward_none_star_compose(*_coconut.reversed(funcs))
def _coconut_forward_none_dubstar_compose(func, *funcs):
"""Forward none-aware double star composition operator (..?**>).
(..?**>)(f, g) is effectively equivalent to (*args, **kwargs) -> g?(**f(*args, **kwargs))."""
return _coconut_base_compose(func, *((f, 2, True) for f in funcs))
def _coconut_back_none_dubstar_compose(*funcs):
"""Backward none-aware double star composition operator (<**?..).
(<**?..)(f, g) is effectively equivalent to (*args, **kwargs) -> f?(**g(*args, **kwargs))."""
return _coconut_forward_none_dubstar_compose(*_coconut.reversed(funcs))
def _coconut_pipe(x, f):
"""Pipe operator (|>). Equivalent to (x, f) -> f(x)."""
return f(x)
def _coconut_star_pipe(xs, f):
"""Star pipe operator (*|>). Equivalent to (xs, f) -> f(*xs)."""
return f(*xs)
def _coconut_dubstar_pipe(kws, f):
"""Double star pipe operator (**|>). Equivalent to (kws, f) -> f(**kws)."""
return f(**kws)
def _coconut_back_pipe(f, x):
"""Backward pipe operator (<|). Equivalent to (f, x) -> f(x)."""
return f(x)
def _coconut_back_star_pipe(f, xs):
"""Backward star pipe operator (<*|). Equivalent to (f, xs) -> f(*xs)."""
return f(*xs)
def _coconut_back_dubstar_pipe(f, kws):
"""Backward double star pipe operator (<**|). Equivalent to (f, kws) -> f(**kws)."""
return f(**kws)
def _coconut_none_pipe(x, f):
"""Nullable pipe operator (|?>). Equivalent to (x, f) -> f(x) if x is not None else None."""
return None if x is None else f(x)
def _coconut_none_star_pipe(xs, f):
"""Nullable star pipe operator (|?*>). Equivalent to (xs, f) -> f(*xs) if xs is not None else None."""
return None if xs is None else f(*xs)
def _coconut_none_dubstar_pipe(kws, f):
"""Nullable double star pipe operator (|?**>). Equivalent to (kws, f) -> f(**kws) if kws is not None else None."""
return None if kws is None else f(**kws)
def _coconut_back_none_pipe(f, x):
"""Nullable backward pipe operator (<?|). Equivalent to (f, x) -> f(x) if x is not None else None."""
return None if x is None else f(x)
def _coconut_back_none_star_pipe(f, xs):
"""Nullable backward star pipe operator (<*?|). Equivalent to (f, xs) -> f(*xs) if xs is not None else None."""
return None if xs is None else f(*xs)
def _coconut_back_none_dubstar_pipe(f, kws):
"""Nullable backward double star pipe operator (<**?|). Equivalent to (kws, f) -> f(**kws) if kws is not None else None."""
return None if kws is None else f(**kws)
def _coconut_assert(cond, msg=None):
"""Assert operator (assert). Asserts condition with optional message."""
if not cond:
assert False, msg if msg is not None else "(assert) got falsey value " + _coconut.repr(cond)
def _coconut_raise(exc=None, from_exc=None):
"""Raise operator (raise). Raises exception with optional cause."""
if exc is None:
raise
if from_exc is not None:
exc.__cause__ = from_exc
raise exc
def _coconut_bool_and(a, b):
"""Boolean and operator (and). Equivalent to (a, b) -> a and b."""
return a and b
def _coconut_bool_or(a, b):
"""Boolean or operator (or). Equivalent to (a, b) -> a or b."""
return a or b
def _coconut_in(a, b):
"""Containment operator (in). Equivalent to (a, b) -> a in b."""
return a in b
def _coconut_not_in(a, b):
"""Negative containment operator (not in). Equivalent to (a, b) -> a not in b."""
return a not in b
def _coconut_none_coalesce(a, b):
"""None coalescing operator (??). Equivalent to (a, b) -> a if a is not None else b."""
return b if a is None else a
def _coconut_minus(a, b=_coconut_sentinel):
"""Minus operator (-). Effectively equivalent to (a, b=None) -> a - b if b is not None else -a."""
if b is _coconut_sentinel:
return -a
return a - b
def _coconut_comma_op(*args):
"""Comma operator (,). Equivalent to (*args) -> args."""
return args
if _coconut_sys.version_info < (3, 5):
def _coconut_matmul(a, b, **kwargs):
"""Matrix multiplication operator (@). Implements operator.matmul on any Python version."""
in_place = kwargs.pop("in_place", False)
if kwargs:
raise _coconut.TypeError("_coconut_matmul() got unexpected keyword arguments " + _coconut.repr(kwargs))
if in_place and _coconut.hasattr(a, "__imatmul__"):
try:
result = a.__imatmul__(b)
except _coconut.NotImplementedError:
pass
else:
if result is not _coconut.NotImplemented:
return result
if _coconut.hasattr(a, "__matmul__"):
try:
result = a.__matmul__(b)
except _coconut.NotImplementedError:
pass
else:
if result is not _coconut.NotImplemented:
return result
if _coconut.hasattr(b, "__rmatmul__"):
try:
result = b.__rmatmul__(a)
except _coconut.NotImplementedError:
pass
else:
if result is not _coconut.NotImplemented:
return result
if "numpy" in (a.__class__.__module__, b.__class__.__module__):
from numpy import matmul
return matmul(a, b)
raise _coconut.TypeError("unsupported operand type(s) for @: " + _coconut.repr(_coconut.type(a)) + " and " + _coconut.repr(_coconut.type(b)))
else:
_coconut_matmul = _coconut.operator.matmul
class scan(_coconut_has_iter):
"""Reduce func over iterable, yielding intermediate results,
optionally starting from initial."""
__slots__ = ("func", "initial")
def __new__(cls, function, iterable, initial=_coconut_sentinel):
self = _coconut_has_iter.__new__(cls, iterable)
self.func = function
self.initial = initial
return self
def __repr__(self):
return "scan(%r, %s%s)" % (self.func, _coconut.repr(self.iter), "" if self.initial is _coconut_sentinel else ", " + _coconut.repr(self.initial))
def __reduce__(self):
return (self.__class__, (self.func, self.iter, self.initial))
def __copy__(self):
return self.__class__(self.func, self.get_new_iter(), self.initial)
def __iter__(self):
acc = self.initial
if acc is not _coconut_sentinel:
yield acc
for item in self.iter:
if acc is _coconut_sentinel:
acc = item
else:
acc = self.func(acc, item)
yield acc
def __len__(self):
if not _coconut.isinstance(self.iter, _coconut.abc.Sized):
return _coconut.NotImplemented
return _coconut.len(self.iter)
class reversed(_coconut_has_iter):
__slots__ = ()
__doc__ = getattr(_coconut.reversed, "__doc__", "<see help(py_reversed)>")
def __new__(cls, iterable):
if _coconut.isinstance(iterable, _coconut.range):
return iterable[::-1]
if _coconut.getattr(iterable, "__reversed__", None) is None or _coconut.isinstance(iterable, (_coconut.list, _coconut.tuple)):
self = _coconut_has_iter.__new__(cls, iterable)
return self
return _coconut.reversed(iterable)
def __repr__(self):
return "reversed(%s)" % (_coconut.repr(self.iter),)
def __reduce__(self):
return (self.__class__, (self.iter,))
def __copy__(self):
return self.__class__(self.get_new_iter())
def __iter__(self):
return _coconut.iter(_coconut.reversed(self.iter))
def __getitem__(self, index):
if _coconut.isinstance(index, _coconut.slice):
return _coconut_iter_getitem(self.iter, _coconut.slice(-(index.start + 1) if index.start is not None else None, -(index.stop + 1) if index.stop else None, -(index.step if index.step is not None else 1)))
return _coconut_iter_getitem(self.iter, -(index + 1))
def __reversed__(self):
return self.iter
def __len__(self):
if not _coconut.isinstance(self.iter, _coconut.abc.Sized):
return _coconut.NotImplemented
return _coconut.len(self.iter)
def __contains__(self, elem):
return elem in self.iter
def count(self, elem):
"""Count the number of times elem appears in the reversed iterable."""
return self.iter.count(elem)
def index(self, elem):
"""Find the index of elem in the reversed iterable."""
return _coconut.len(self.iter) - self.iter.index(elem) - 1
def __fmap__(self, func):
return self.__class__(_coconut_map(func, self.iter))
class flatten(_coconut_has_iter):
"""Flatten an iterable of iterables into a single iterable.
Only flattens the top level of the iterable."""
__slots__ = ("levels", "_made_reit")
def __new__(cls, iterable, levels=1):
if levels is not None:
levels = _coconut.operator.index(levels)
if levels < 0:
raise _coconut.ValueError("flatten: levels cannot be negative")
if levels == 0:
return iterable
self = _coconut_has_iter.__new__(cls, iterable)
self.levels = levels
self._made_reit = False
return self
def get_new_iter(self):
"""Tee the underlying iterator."""
with self.lock:
if not self._made_reit:
for i in _coconut.reversed(_coconut.range(0 if self.levels is None else self.levels + 1)):
mapper = _coconut_reiterable
for _ in _coconut.range(i):
mapper = _coconut.functools.partial(_coconut_map, mapper)
self.iter = mapper(self.iter)
self._made_reit = True
return self.iter
def __iter__(self):
if self.levels is None:
return self._iter_all_levels()
new_iter = self.iter
for _ in _coconut.range(self.levels):
new_iter = _coconut.itertools.chain.from_iterable(new_iter)
return new_iter
def _iter_all_levels(self, new=False):
"""Iterate over all levels of the iterable."""
for item in (self.get_new_iter() if new else self.iter):
if _coconut.isinstance(item, _coconut.abc.Iterable):
for subitem in self.__class__(item, None):