Skip to content

Human

A collection of instruments for converting data to format is convenient for humans.

The module contains the following functions:

  • to_human_size(size) - Returns a humanized string: 200 bytes | 1 KB | 1.5 MB etc.

clean_cache_human_size()

Reset of variable _cach_human_size.

Source code in src\xloft\human.py
29
30
31
32
def clean_cache_human_size() -> None:
    """Reset of variable _cach_human_size."""
    global _cache_human_size  # noqa: PLW0603
    _cache_human_size = {}

get_cache_human_size()

Get a copy of variable _cach_human_size.

Hint: To tests.

Source code in src\xloft\human.py
21
22
23
24
25
26
def get_cache_human_size() -> dict[int, str]:
    """Get a copy of variable _cach_human_size.

    Hint: To tests.
    """
    return _cache_human_size.copy()

to_human_size(n_bytes)

Convert number of bytes to readable format.

Examples:

>>> from xloft import to_human_size
>>> to_human_size(200)
200 bytes
>>> to_human_size(1048576)
1 MB
>>> to_human_size(1048575)
1023.999 KB

Parameters:

Name Type Description Default
n_bytes int

The number of bytes.

required

Returns:

Type Description
str

Returns a humanized string: 200 bytes | 1 KB | 1.5 MB etc.

Source code in src\xloft\human.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def to_human_size(n_bytes: int) -> str:
    """Convert number of bytes to readable format.

    Examples:
        >>> from xloft import to_human_size
        >>> to_human_size(200)
        200 bytes
        >>> to_human_size(1048576)
        1 MB
        >>> to_human_size(1048575)
        1023.999 KB

    Args:
        n_bytes: The number of bytes.

    Returns:
        Returns a humanized string: 200 bytes | 1 KB | 1.5 MB etc.
    """
    result: str | None = _cache_human_size.get(n_bytes)
    if result is not None:
        return result
    idx: int = math.floor(math.log(n_bytes) / math.log(1024))
    ndigits: int = [0, 3, 6, 9, 12][idx]
    human_size: int | float = n_bytes if n_bytes < 1024 else abs(round(n_bytes / pow(1024, idx), ndigits))
    order = ["bytes", "KB", "MB", "GB", "TB"][idx]
    if math.modf(human_size)[0] == 0.0:
        human_size = int(human_size)
    result = f"{human_size} {order}"
    _cache_human_size[n_bytes] = result
    return result