🔍 Code Extractor

function human_readable_size

Maturity: 53

Converts a byte size value into a human-readable string format with appropriate unit suffixes (B, KB, MB, GB, TB).

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
159 - 178
Complexity:
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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_file_size 81.0% similar

    Converts a file size in bytes to a human-readable string format with appropriate units (B, KB, MB, GB, TB).

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
  • function format_file_size_v1 80.3% similar

    Converts a file size in bytes to a human-readable string format with appropriate units (B, KB, MB, GB, TB).

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
  • function bytes_to_unicode 46.8% similar

    Converts a bytes object to a Unicode string using UTF-8 encoding, or returns the input unchanged if it's not a bytes object.

    From: /tf/active/vicechatdev/patches/util.py
  • function _int_to_bytes 43.3% similar

    Converts a signed integer to its little-endian byte representation, automatically determining the minimum number of bytes needed based on the integer's bit length.

    From: /tf/active/vicechatdev/patches/util.py
  • function format_datetime_v1 35.3% similar

    Converts an ISO format datetime string into a human-readable UTC datetime string formatted as 'YYYY-MM-DD HH:MM:SS UTC'.

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
← Back to Browse