Created
August 18, 2023 03:19
-
-
Save Techcable/9a2426b6e1a1fe2e7869cd67bb9844a6 to your computer and use it in GitHub Desktop.
Minature python library which formats bytes for user display
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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