human_size() - Format Bytes

  • String Formatting – Converts raw byte values back into clean, readable strings like 2 GiB or 50 GB.
  • Smart Decimal Precision – Auto-rounds and formats fractional sizes cleanly up to 2 decimal places.
  • Dual Bases – Supports base=2 (binary 1024) and base=10 (decimal 1000) formatting output units.
Signature
sizelib.human_size(size_bytes: int | float, base: int = 2) -> str

Output Unit Hierarchy Scale

BaseDivisorUnit Escalation Order
Base 2 (Binary)1024B → KiB → MiB → GiB → TiB → PiB → EiB → ZiB → YiB
Base 10 (Decimal)1000B → KB → MB → GB → TB → PB → EB → ZB → YB
human_size() - Usage
from sizelib import human_size, size

# Default binary formatting (base 2 / 1024)
print(human_size(10485760))              # Output: 10 MiB
print(human_size(1500000))               # Output: 1.43 MiB
print(human_size(size.gib(2.5)))         # Output: 2.50 GiB

# Decimal formatting (base 10 / 1000)
print(human_size(5000000000, base=10))   # Output: 5 GB
print(human_size(1500000, base=10))      # Output: 1.50 MB
print(human_size(size.gb(50), base=10))  # Output: 50 GB
human_size() - Edge Cases & Exceptions
from sizelib import human_size

# Zero byte input
print(human_size(0))                     # Output: 0 B

# Negative values raise ValueError
try:
    human_size(-5)
except ValueError as e:
    print(e)                             # Output: Size cannot be negative

# Invalid base parameter raises ValueError
try:
    human_size(100, base=5)
except ValueError as e:
    print(e)                             # Output: Base must be 2 or 10