Skip to content

Instantly share code, notes, and snippets.

@nobkd
Last active March 4, 2023 21:42
Show Gist options
  • Save nobkd/2de93463093be2c8ad938635643249b6 to your computer and use it in GitHub Desktop.
Save nobkd/2de93463093be2c8ad938635643249b6 to your computer and use it in GitHub Desktop.
Python ^3.10: Function for dividing a number of bytes to a suitable data unit
def unit_bytes(bytes: int | float, precision: int = 2, separate: bool = False) -> str | tuple[int | float, str]:
"""Divides a number of bytes to a suitable data unit
Args:
bytes (int | float): the number of bytes to be converted
precision (int): the decimal place rounding precision for the output
separate (bool): if bytes and unit should be separate values when returned
Returns:
str | tuple[int | float, str]: the divided bytes rounded to the specified precision of decimal places combined with the data unit
"""
# Byte
base_unit: str = 'B'
# -, Kibi-, Mibi-, Gibi-, Tebi-, Pebi-, Exbi-, Zebi-, Yobi-
units: list[str] = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi']
for i, unit in enumerate(units):
if abs(bytes) >= 1024 and i < len(units) - 1:
bytes /= 1024
else:
if not separate:
return f'{round(bytes, precision)}{unit}{base_unit}'
else:
return round(bytes, precision), f'{unit}{base_unit}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment