MCPcopy Create free account
hub / github.com/dask/dask / parse_bytes

Function parse_bytes

dask/utils.py:1585–1639  ·  view source on GitHub ↗

Parse byte string to numbers >>> from dask.utils import parse_bytes >>> parse_bytes('100') 100 >>> parse_bytes('100 MB') 100000000 >>> parse_bytes('100M') 100000000 >>> parse_bytes('5kB') 5000 >>> parse_bytes('5.4 kB') 5400 >>> parse_bytes('1kiB')

(s: float | str)

Source from the content-addressed store, hash-verified

1583
1584
1585def parse_bytes(s: float | str) -> int:
1586 """Parse byte string to numbers
1587
1588 >>> from dask.utils import parse_bytes
1589 >>> parse_bytes('100')
1590 100
1591 >>> parse_bytes('100 MB')
1592 100000000
1593 >>> parse_bytes('100M')
1594 100000000
1595 >>> parse_bytes('5kB')
1596 5000
1597 >>> parse_bytes('5.4 kB')
1598 5400
1599 >>> parse_bytes('1kiB')
1600 1024
1601 >>> parse_bytes('1e6')
1602 1000000
1603 >>> parse_bytes('1e6 kB')
1604 1000000000
1605 >>> parse_bytes('MB')
1606 1000000
1607 >>> parse_bytes(123)
1608 123
1609 >>> parse_bytes('5 foos')
1610 Traceback (most recent call last):
1611 ...
1612 ValueError: Could not interpret 'foos' as a byte unit
1613 """
1614 if isinstance(s, (int, float)):
1615 return int(s)
1616 s = s.replace(" ", "")
1617 if not any(char.isdigit() for char in s):
1618 s = "1" + s
1619
1620 for i in range(len(s) - 1, -1, -1):
1621 if not s[i].isalpha():
1622 break
1623 index = i + 1
1624
1625 prefix = s[:index]
1626 suffix = s[index:]
1627
1628 try:
1629 n = float(prefix)
1630 except ValueError as e:
1631 raise ValueError("Could not interpret '%s' as a number" % prefix) from e
1632
1633 try:
1634 multiplier = byte_sizes[suffix.lower()]
1635 except KeyError as e:
1636 raise ValueError("Could not interpret '%s' as a byte unit" % suffix) from e
1637
1638 result = n * multiplier
1639 return int(result)
1640
1641
1642byte_sizes = {

Callers 14

read_bytesFunction · 0.90
read_textFunction · 0.90
repartition_sizeFunction · 0.90
_sizeMethod · 0.90
_fragment_to_tableMethod · 0.90
read_pandasFunction · 0.90
read_sql_queryFunction · 0.90
aggregate_row_groupsFunction · 0.90
_infer_split_row_groupsFunction · 0.90
test_parse_bytesFunction · 0.90
normalize_chunksFunction · 0.90

Calls 2

anyFunction · 0.85
replaceMethod · 0.45

Tested by 1

test_parse_bytesFunction · 0.72