forked from dask/dask
/
utils.py
1989 lines (1606 loc) · 51.1 KB
/
utils.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
from __future__ import annotations
import codecs
import functools
import inspect
import os
import re
import shutil
import sys
import tempfile
import uuid
import warnings
from collections.abc import Hashable, Iterable, Iterator, Mapping, Set
from contextlib import contextmanager, nullcontext, suppress
from datetime import datetime, timedelta
from errno import ENOENT
from functools import lru_cache
from importlib import import_module
from numbers import Integral, Number
from operator import add
from threading import Lock
from typing import Any, ClassVar, Literal, TypeVar, overload
from weakref import WeakValueDictionary
import tlz as toolz
from dask.core import get_deps
K = TypeVar("K")
V = TypeVar("V")
T = TypeVar("T")
system_encoding = sys.getdefaultencoding()
if system_encoding == "ascii":
system_encoding = "utf-8"
def apply(func, args, kwargs=None):
if kwargs:
return func(*args, **kwargs)
else:
return func(*args)
def _deprecated(
*,
version: str | None = None,
after_version: str | None = None,
message: str | None = None,
use_instead: str | None = None,
category: type[Warning] = FutureWarning,
):
"""Decorator to mark a function as deprecated
Parameters
----------
version : str, optional
Version of Dask in which the function was deprecated. If specified, the version
will be included in the default warning message. This should no longer be used
after the introduction of automated versioning system.
after_version : str, optional
Version of Dask after which the function was deprecated. If specified, the
version will be included in the default warning message.
message : str, optional
Custom warning message to raise.
use_instead : str, optional
Name of function to use in place of the deprecated function.
If specified, this will be included in the default warning
message.
category : type[Warning], optional
Type of warning to raise. Defaults to ``FutureWarning``.
Examples
--------
>>> from dask.utils import _deprecated
>>> @_deprecated(after_version="X.Y.Z", use_instead="bar")
... def foo():
... return "baz"
"""
def decorator(func):
if message is None:
msg = f"{func.__name__} "
if after_version is not None:
msg += f"was deprecated after version {after_version} "
elif version is not None:
msg += f"was deprecated in version {version} "
else:
msg += "is deprecated "
msg += "and will be removed in a future release."
if use_instead is not None:
msg += f" Please use {use_instead} instead."
else:
msg = message
@functools.wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(msg, category=category, stacklevel=2)
return func(*args, **kwargs)
return wrapper
return decorator
def deepmap(func, *seqs):
"""Apply function inside nested lists
>>> inc = lambda x: x + 1
>>> deepmap(inc, [[1, 2], [3, 4]])
[[2, 3], [4, 5]]
>>> add = lambda x, y: x + y
>>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]])
[[11, 22], [33, 44]]
"""
if isinstance(seqs[0], (list, Iterator)):
return [deepmap(func, *items) for items in zip(*seqs)]
else:
return func(*seqs)
@_deprecated()
def homogeneous_deepmap(func, seq):
if not seq:
return seq
n = 0
tmp = seq
while isinstance(tmp, list):
n += 1
tmp = tmp[0]
return ndeepmap(n, func, seq)
def ndeepmap(n, func, seq):
"""Call a function on every element within a nested container
>>> def inc(x):
... return x + 1
>>> L = [[1, 2], [3, 4, 5]]
>>> ndeepmap(2, inc, L)
[[2, 3], [4, 5, 6]]
"""
if n == 1:
return [func(item) for item in seq]
elif n > 1:
return [ndeepmap(n - 1, func, item) for item in seq]
elif isinstance(seq, list):
return func(seq[0])
else:
return func(seq)
def import_required(mod_name, error_msg):
"""Attempt to import a required dependency.
Raises a RuntimeError if the requested module is not available.
"""
try:
return import_module(mod_name)
except ImportError as e:
raise RuntimeError(error_msg) from e
@contextmanager
def tmpfile(extension="", dir=None):
"""
Function to create and return a unique temporary file with the given extension, if provided.
Parameters
----------
extension : str
The extension of the temporary file to be created
dir : str
If ``dir`` is not None, the file will be created in that directory; otherwise,
Python's default temporary directory is used.
Returns
-------
out : str
Path to the temporary file
See Also
--------
NamedTemporaryFile : Built-in alternative for creating temporary files
tmp_path : pytest fixture for creating a temporary directory unique to the test invocation
Notes
-----
This context manager is particularly useful on Windows for opening temporary files multiple times.
"""
extension = "." + extension.lstrip(".")
handle, filename = tempfile.mkstemp(extension, dir=dir)
os.close(handle)
os.remove(filename)
try:
yield filename
finally:
if os.path.exists(filename):
with suppress(OSError): # sometimes we can't remove a generated temp file
if os.path.isdir(filename):
shutil.rmtree(filename)
else:
os.remove(filename)
@contextmanager
def tmpdir(dir=None):
"""
Function to create and return a unique temporary directory.
Parameters
----------
dir : str
If ``dir`` is not None, the directory will be created in that directory; otherwise,
Python's default temporary directory is used.
Returns
-------
out : str
Path to the temporary directory
Notes
-----
This context manager is particularly useful on Windows for opening temporary directories multiple times.
"""
dirname = tempfile.mkdtemp(dir=dir)
try:
yield dirname
finally:
if os.path.exists(dirname):
if os.path.isdir(dirname):
with suppress(OSError):
shutil.rmtree(dirname)
else:
with suppress(OSError):
os.remove(dirname)
@contextmanager
def filetext(text, extension="", open=open, mode="w"):
with tmpfile(extension=extension) as filename:
f = open(filename, mode=mode)
try:
f.write(text)
finally:
try:
f.close()
except AttributeError:
pass
yield filename
@contextmanager
def changed_cwd(new_cwd):
old_cwd = os.getcwd()
os.chdir(new_cwd)
try:
yield
finally:
os.chdir(old_cwd)
@contextmanager
def tmp_cwd(dir=None):
with tmpdir(dir) as dirname:
with changed_cwd(dirname):
yield dirname
class IndexCallable:
"""Provide getitem syntax for functions
>>> def inc(x):
... return x + 1
>>> I = IndexCallable(inc)
>>> I[3]
4
"""
__slots__ = ("fn",)
def __init__(self, fn):
self.fn = fn
def __getitem__(self, key):
return self.fn(key)
@contextmanager
def filetexts(d, open=open, mode="t", use_tmpdir=True):
"""Dumps a number of textfiles to disk
Parameters
----------
d : dict
a mapping from filename to text like {'a.csv': '1,1\n2,2'}
Since this is meant for use in tests, this context manager will
automatically switch to a temporary current directory, to avoid
race conditions when running tests in parallel.
"""
with (tmp_cwd() if use_tmpdir else nullcontext()):
for filename, text in d.items():
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
f = open(filename, "w" + mode)
try:
f.write(text)
finally:
try:
f.close()
except AttributeError:
pass
yield list(d)
for filename in d:
if os.path.exists(filename):
with suppress(OSError):
os.remove(filename)
def concrete(seq):
"""Make nested iterators concrete lists
>>> data = [[1, 2], [3, 4]]
>>> seq = iter(map(iter, data))
>>> concrete(seq)
[[1, 2], [3, 4]]
"""
if isinstance(seq, Iterator):
seq = list(seq)
if isinstance(seq, (tuple, list)):
seq = list(map(concrete, seq))
return seq
def pseudorandom(n: int, p, random_state=None):
"""Pseudorandom array of integer indexes
>>> pseudorandom(5, [0.5, 0.5], random_state=123)
array([1, 0, 0, 1, 1], dtype=int8)
>>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], random_state=5)
array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8)
"""
import numpy as np
p = list(p)
cp = np.cumsum([0] + p)
assert np.allclose(1, cp[-1])
assert len(p) < 256
if not isinstance(random_state, np.random.RandomState):
random_state = np.random.RandomState(random_state)
x = random_state.random_sample(n)
out = np.empty(n, dtype="i1")
for i, (low, high) in enumerate(zip(cp[:-1], cp[1:])):
out[(x >= low) & (x < high)] = i
return out
def random_state_data(n: int, random_state=None) -> list:
"""Return a list of arrays that can initialize
``np.random.RandomState``.
Parameters
----------
n : int
Number of arrays to return.
random_state : int or np.random.RandomState, optional
If an int, is used to seed a new ``RandomState``.
"""
import numpy as np
if not all(
hasattr(random_state, attr) for attr in ["normal", "beta", "bytes", "uniform"]
):
random_state = np.random.RandomState(random_state)
random_data = random_state.bytes(624 * n * 4) # `n * 624` 32-bit integers
l = list(np.frombuffer(random_data, dtype=np.uint32).reshape((n, -1)))
assert len(l) == n
return l
def is_integer(i) -> bool:
"""
>>> is_integer(6)
True
>>> is_integer(42.0)
True
>>> is_integer('abc')
False
"""
return isinstance(i, Integral) or (isinstance(i, float) and i.is_integer())
ONE_ARITY_BUILTINS = {
abs,
all,
any,
ascii,
bool,
bytearray,
bytes,
callable,
chr,
classmethod,
complex,
dict,
dir,
enumerate,
eval,
float,
format,
frozenset,
hash,
hex,
id,
int,
iter,
len,
list,
max,
min,
next,
oct,
open,
ord,
range,
repr,
reversed,
round,
set,
slice,
sorted,
staticmethod,
str,
sum,
tuple,
type,
vars,
zip,
memoryview,
}
MULTI_ARITY_BUILTINS = {
compile,
delattr,
divmod,
filter,
getattr,
hasattr,
isinstance,
issubclass,
map,
pow,
setattr,
}
def getargspec(func):
"""Version of inspect.getargspec that works with partial and warps."""
if isinstance(func, functools.partial):
return getargspec(func.func)
func = getattr(func, "__wrapped__", func)
if isinstance(func, type):
return inspect.getfullargspec(func.__init__)
else:
return inspect.getfullargspec(func)
def takes_multiple_arguments(func, varargs=True):
"""Does this function take multiple arguments?
>>> def f(x, y): pass
>>> takes_multiple_arguments(f)
True
>>> def f(x): pass
>>> takes_multiple_arguments(f)
False
>>> def f(x, y=None): pass
>>> takes_multiple_arguments(f)
False
>>> def f(*args): pass
>>> takes_multiple_arguments(f)
True
>>> class Thing:
... def __init__(self, a): pass
>>> takes_multiple_arguments(Thing)
False
"""
if func in ONE_ARITY_BUILTINS:
return False
elif func in MULTI_ARITY_BUILTINS:
return True
try:
spec = getargspec(func)
except Exception:
return False
try:
is_constructor = spec.args[0] == "self" and isinstance(func, type)
except Exception:
is_constructor = False
if varargs and spec.varargs:
return True
ndefaults = 0 if spec.defaults is None else len(spec.defaults)
return len(spec.args) - ndefaults - is_constructor > 1
def get_named_args(func) -> list[str]:
"""Get all non ``*args/**kwargs`` arguments for a function"""
s = inspect.signature(func)
return [
n
for n, p in s.parameters.items()
if p.kind in [p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY, p.KEYWORD_ONLY]
]
class Dispatch:
"""Simple single dispatch."""
def __init__(self, name=None):
self._lookup = {}
self._lazy = {}
if name:
self.__name__ = name
def register(self, type, func=None):
"""Register dispatch of `func` on arguments of type `type`"""
def wrapper(func):
if isinstance(type, tuple):
for t in type:
self.register(t, func)
else:
self._lookup[type] = func
return func
return wrapper(func) if func is not None else wrapper
def register_lazy(self, toplevel, func=None):
"""
Register a registration function which will be called if the
*toplevel* module (e.g. 'pandas') is ever loaded.
"""
def wrapper(func):
self._lazy[toplevel] = func
return func
return wrapper(func) if func is not None else wrapper
def dispatch(self, cls):
"""Return the function implementation for the given ``cls``"""
lk = self._lookup
for cls2 in cls.__mro__:
try:
impl = lk[cls2]
except KeyError:
pass
else:
if cls is not cls2:
# Cache lookup
lk[cls] = impl
return impl
# Is a lazy registration function present?
toplevel, _, _ = cls2.__module__.partition(".")
try:
register = self._lazy.pop(toplevel)
except KeyError:
pass
else:
register()
return self.dispatch(cls) # recurse
raise TypeError(f"No dispatch for {cls}")
def __call__(self, arg, *args, **kwargs):
"""
Call the corresponding method based on type of argument.
"""
meth = self.dispatch(type(arg))
return meth(arg, *args, **kwargs)
@property
def __doc__(self):
try:
func = self.dispatch(object)
return func.__doc__
except TypeError:
return "Single Dispatch for %s" % self.__name__
def ensure_not_exists(filename) -> None:
"""
Ensure that a file does not exist.
"""
try:
os.unlink(filename)
except OSError as e:
if e.errno != ENOENT:
raise
def _skip_doctest(line):
# NumPy docstring contains cursor and comment only example
stripped = line.strip()
if stripped == ">>>" or stripped.startswith(">>> #"):
return line
elif ">>>" in stripped and "+SKIP" not in stripped:
if "# doctest:" in line:
return line + ", +SKIP"
else:
return line + " # doctest: +SKIP"
else:
return line
def skip_doctest(doc):
if doc is None:
return ""
return "\n".join([_skip_doctest(line) for line in doc.split("\n")])
def extra_titles(doc):
lines = doc.split("\n")
titles = {
i: lines[i].strip()
for i in range(len(lines) - 1)
if lines[i + 1].strip() and all(c == "-" for c in lines[i + 1].strip())
}
seen = set()
for i, title in sorted(titles.items()):
if title in seen:
new_title = "Extra " + title
lines[i] = lines[i].replace(title, new_title)
lines[i + 1] = lines[i + 1].replace("-" * len(title), "-" * len(new_title))
else:
seen.add(title)
return "\n".join(lines)
def ignore_warning(doc, cls, name, extra="", skipblocks=0):
"""Expand docstring by adding disclaimer and extra text"""
import inspect
if inspect.isclass(cls):
l1 = "This docstring was copied from {}.{}.{}.\n\n".format(
cls.__module__,
cls.__name__,
name,
)
else:
l1 = f"This docstring was copied from {cls.__name__}.{name}.\n\n"
l2 = "Some inconsistencies with the Dask version may exist."
i = doc.find("\n\n")
if i != -1:
# Insert our warning
head = doc[: i + 2]
tail = doc[i + 2 :]
while skipblocks > 0:
i = tail.find("\n\n")
head = tail[: i + 2]
tail = tail[i + 2 :]
skipblocks -= 1
# Indentation of next line
indent = re.match(r"\s*", tail).group(0)
# Insert the warning, indented, with a blank line before and after
if extra:
more = [indent, extra.rstrip("\n") + "\n\n"]
else:
more = []
bits = [head, indent, l1, indent, l2, "\n\n"] + more + [tail]
doc = "".join(bits)
return doc
def unsupported_arguments(doc, args):
"""Mark unsupported arguments with a disclaimer"""
lines = doc.split("\n")
for arg in args:
subset = [
(i, line)
for i, line in enumerate(lines)
if re.match(r"^\s*" + arg + " ?:", line)
]
if len(subset) == 1:
[(i, line)] = subset
lines[i] = line + " (Not supported in Dask)"
return "\n".join(lines)
def _derived_from(cls, method, ua_args=None, extra="", skipblocks=0):
"""Helper function for derived_from to ease testing"""
ua_args = ua_args or []
# do not use wraps here, as it hides keyword arguments displayed
# in the doc
original_method = getattr(cls, method.__name__)
doc = getattr(original_method, "__doc__", None)
if isinstance(original_method, property):
# some things like SeriesGroupBy.unique are generated.
original_method = original_method.fget
if not doc:
doc = getattr(original_method, "__doc__", None)
if doc is None:
doc = ""
# pandas DataFrame/Series sometimes override methods without setting __doc__
if not doc and cls.__name__ in {"DataFrame", "Series"}:
for obj in cls.mro():
obj_method = getattr(obj, method.__name__, None)
if obj_method is not None and obj_method.__doc__:
doc = obj_method.__doc__
break
# Insert disclaimer that this is a copied docstring
if doc:
doc = ignore_warning(
doc, cls, method.__name__, extra=extra, skipblocks=skipblocks
)
elif extra:
doc += extra.rstrip("\n") + "\n\n"
# Mark unsupported arguments
try:
method_args = get_named_args(method)
original_args = get_named_args(original_method)
not_supported = [m for m in original_args if m not in method_args]
except ValueError:
not_supported = []
if len(ua_args) > 0:
not_supported.extend(ua_args)
if len(not_supported) > 0:
doc = unsupported_arguments(doc, not_supported)
doc = skip_doctest(doc)
doc = extra_titles(doc)
return doc
def derived_from(original_klass, version=None, ua_args=None, skipblocks=0):
"""Decorator to attach original class's docstring to the wrapped method.
The output structure will be: top line of docstring, disclaimer about this
being auto-derived, any extra text associated with the method being patched,
the body of the docstring and finally, the list of keywords that exist in
the original method but not in the dask version.
Parameters
----------
original_klass: type
Original class which the method is derived from
version : str
Original package version which supports the wrapped method
ua_args : list
List of keywords which Dask doesn't support. Keywords existing in
original but not in Dask will automatically be added.
skipblocks : int
How many text blocks (paragraphs) to skip from the start of the
docstring. Useful for cases where the target has extra front-matter.
"""
ua_args = ua_args or []
def wrapper(method):
try:
extra = getattr(method, "__doc__", None) or ""
method.__doc__ = _derived_from(
original_klass,
method,
ua_args=ua_args,
extra=extra,
skipblocks=skipblocks,
)
return method
except AttributeError:
module_name = original_klass.__module__.split(".")[0]
@functools.wraps(method)
def wrapped(*args, **kwargs):
msg = f"Base package doesn't support '{method.__name__}'."
if version is not None:
msg2 = " Use {0} {1} or later to use this method."
msg += msg2.format(module_name, version)
raise NotImplementedError(msg)
return wrapped
return wrapper
def funcname(func) -> str:
"""Get the name of a function."""
# functools.partial
if isinstance(func, functools.partial):
return funcname(func.func)
# methodcaller
if isinstance(func, methodcaller):
return func.method[:50]
module_name = getattr(func, "__module__", None) or ""
type_name = getattr(type(func), "__name__", None) or ""
# toolz.curry
if "toolz" in module_name and "curry" == type_name:
return func.func_name[:50]
# multipledispatch objects
if "multipledispatch" in module_name and "Dispatcher" == type_name:
return func.name[:50]
# numpy.vectorize objects
if "numpy" in module_name and "vectorize" == type_name:
return ("vectorize_" + funcname(func.pyfunc))[:50]
# All other callables
try:
name = func.__name__
if name == "<lambda>":
return "lambda"
return name[:50]
except AttributeError:
return str(func)[:50]
def typename(typ: Any, short: bool = False) -> str:
"""
Return the name of a type
Examples
--------
>>> typename(int)
'int'
>>> from dask.core import literal
>>> typename(literal)
'dask.core.literal'
>>> typename(literal, short=True)
'dask.literal'
"""
if not isinstance(typ, type):
return typename(type(typ))
try:
if not typ.__module__ or typ.__module__ == "builtins":
return typ.__name__
else:
if short:
module, *_ = typ.__module__.split(".")
else:
module = typ.__module__
return module + "." + typ.__name__
except AttributeError:
return str(typ)
def ensure_bytes(s) -> bytes:
"""Attempt to turn `s` into bytes.
Parameters
----------
s : Any
The object to be converted. Will correctly handled
* str
* bytes
* objects implementing the buffer protocol (memoryview, ndarray, etc.)
Returns
-------
b : bytes
Raises
------
TypeError
When `s` cannot be converted
Examples
--------
>>> ensure_bytes('123')
b'123'
>>> ensure_bytes(b'123')
b'123'
>>> ensure_bytes(bytearray(b'123'))
b'123'
"""
if isinstance(s, bytes):
return s
elif hasattr(s, "encode"):
return s.encode()
else:
try:
return bytes(s)
except Exception as e:
raise TypeError(
f"Object {s} is neither a bytes object nor can be encoded to bytes"
) from e
def ensure_unicode(s) -> str:
"""Turn string or bytes to string
>>> ensure_unicode('123')
'123'
>>> ensure_unicode(b'123')
'123'
"""
if isinstance(s, str):
return s
elif hasattr(s, "decode"):
return s.decode()
else:
try:
return codecs.decode(s)
except Exception as e:
raise TypeError(
f"Object {s} is neither a str object nor can be decoded to str"
) from e
def digit(n, k, base):
"""
>>> digit(1234, 0, 10)
4
>>> digit(1234, 1, 10)
3
>>> digit(1234, 2, 10)
2
>>> digit(1234, 3, 10)
1
"""
return n // base**k % base
def insert(tup, loc, val):
"""
>>> insert(('a', 'b', 'c'), 0, 'x')
('x', 'b', 'c')
"""
L = list(tup)
L[loc] = val
return tuple(L)
def dependency_depth(dsk):
deps, _ = get_deps(dsk)
@lru_cache(maxsize=None)
def max_depth_by_deps(key):
if not deps[key]:
return 1
d = 1 + max(max_depth_by_deps(dep_key) for dep_key in deps[key])
return d
return max(max_depth_by_deps(dep_key) for dep_key in deps.keys())
def memory_repr(num):
for x in ["bytes", "KB", "MB", "GB", "TB"]:
if num < 1024.0:
return f"{num:3.1f} {x}"
num /= 1024.0
def asciitable(columns, rows):
"""Formats an ascii table for given columns and rows.
Parameters