function human_readable_size
Converts a byte size value into a human-readable string format with appropriate unit suffixes (B, KB, MB, GB, TB).
/tf/active/vicechatdev/CDocs/utils/__init__.py
159 - 178
simple
Purpose
This utility function transforms raw byte counts into user-friendly size representations by automatically selecting the most appropriate unit (bytes, kilobytes, megabytes, gigabytes, or terabytes) and formatting the output with two decimal places. It's commonly used for displaying file sizes, memory usage, or data transfer amounts in user interfaces and logs.
Source Code
def human_readable_size(size_bytes: int) -> str:
"""
Convert bytes to human-readable size.
Args:
size_bytes: Size in bytes
Returns:
Human-readable size string
"""
if size_bytes == 0:
return "0 B"
size_names = ["B", "KB", "MB", "GB", "TB"]
i = 0
while size_bytes >= 1024 and i < len(size_names) - 1:
size_bytes /= 1024
i += 1
return f"{size_bytes:.2f} {size_names[i]}"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
size_bytes |
int | - | positional_or_keyword |
Parameter Details
size_bytes: An integer representing the size in bytes to be converted. Must be a non-negative integer. Zero returns '0 B', and larger values are automatically scaled to the appropriate unit (1024 bytes = 1 KB).
Return Value
Type: str
Returns a string containing the converted size with two decimal places followed by the appropriate unit suffix. Format: '{value:.2f} {unit}' where value is the scaled number and unit is one of: B, KB, MB, GB, or TB. Example outputs: '0 B', '1.50 KB', '2.34 MB', '1.00 GB'.
Usage Example
# Basic usage examples
size1 = human_readable_size(0)
print(size1) # Output: '0 B'
size2 = human_readable_size(1024)
print(size2) # Output: '1.00 KB'
size3 = human_readable_size(1536)
print(size3) # Output: '1.50 KB'
size4 = human_readable_size(1048576)
print(size4) # Output: '1.00 MB'
size5 = human_readable_size(5368709120)
print(size5) # Output: '5.00 GB'
# Practical use case: displaying file sizes
file_size_bytes = 2457600
readable_size = human_readable_size(file_size_bytes)
print(f"File size: {readable_size}") # Output: 'File size: 2.34 MB'
Best Practices
- This function uses base-1024 conversion (binary) rather than base-1000 (decimal), which is the standard for computing contexts (1 KB = 1024 bytes, not 1000 bytes)
- The function handles zero bytes as a special case to avoid division issues
- The maximum unit is TB (terabytes); values larger than 1024 TB will still be displayed in TB units
- Input should be a non-negative integer; negative values will produce incorrect results
- The output is always formatted with exactly 2 decimal places for consistency
- This function is pure and has no side effects, making it safe for concurrent use
- Consider wrapping calls in try-except if the input source is untrusted, as non-integer inputs will raise a TypeError
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function format_file_size 81.0% similar
-
function format_file_size_v1 80.3% similar
-
function bytes_to_unicode 46.8% similar
-
function _int_to_bytes 43.3% similar
-
function format_datetime_v1 35.3% similar