Skip to content

Instantly share code, notes, and snippets.

@Techcable
Created August 18, 2023 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Techcable/9a2426b6e1a1fe2e7869cd67bb9844a6 to your computer and use it in GitHub Desktop.
Save Techcable/9a2426b6e1a1fe2e7869cd67bb9844a6 to your computer and use it in GitHub Desktop.
Minature python library which formats bytes for user display
from decimal import Decimal
from enum import IntEnum
from numbers import Real
class ByteUnit(IntEnum):
BYTE = 1
KILLIBYTE = 1024**1
MEGABYTE = 1024**2
GIGABYTE = 1024**3
TERABYTE = 1024**4
def __str__(self):
if self == ByteUnit.BYTE:
return "B"
else:
return f"{self.name[0]}iB"
class FormattedBytes:
coefficient: Real
unit: ByteUnit
value: int
def __init__(self, val: int, /, unit: ByteUnit | None = None):
assert isinstance(val, int), f"Value must be integer: {val}"
if unit is None:
self.value = val
val = Decimal(val)
unit_val: int = 1
while val >= 1024:
val /= 1024
unit_val *= 1024
self.coefficient = val
if self.coefficient == (int_coeff := int(self.coefficient)):
self.coefficient = int_coeff
unit = ByteUnit(unit_val)
else:
self.coefficient = val
self.value = val * int(unit)
assert unit is not None
self.unit = unit
def __int__(self) -> int:
return self.value
def __repr__(self):
return f"<FormattedBytes(value={self.value}): {self!s}>"
def __str__(self) -> str:
exact_coefficient = isinstance(self.coefficient, int)
return format(self, "" if exact_coefficient else ".3f")
def __format__(self, spec: str) -> str:
return f"{self.coefficient:{spec}} {self.unit}"
__all__ = ("ByteUnit", "FormattedBytes")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment