Skip to content

Commit 2a29af4

Browse files
committed
Cleanup file_size and add extra documentation
1 parent bf68307 commit 2a29af4

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/human_readable/files.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33

44
def file_size(
5-
value: int, binary: bool = False, gnu: bool = False, formatting: str = ".1f", small_formatting: str = "",
5+
value: int,
6+
binary: bool = False,
7+
gnu: bool = False,
8+
formatting: str = ".1f",
9+
small_formatting: str = "",
610
) -> str:
711
"""Return human-readable file size.
812
@@ -20,8 +24,8 @@ def file_size(
2024
value: size number.
2125
binary: binary format. Defaults to False.
2226
gnu: GNU format. Defaults to False.
23-
formatting: format pattern. Defaults to ".1f".
24-
small_formatting: format pattern for small values. Defaults to "".
27+
formatting: format pattern (applied to a float). Defaults to ".1f".
28+
small_formatting: format pattern for small values (applied to an int). Defaults to "".
2529
2630
Returns:
2731
str: file size in natural language.
@@ -34,19 +38,18 @@ def file_size(
3438
suffixes = (" kB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB")
3539

3640
base = 1024 if (gnu or binary) else 1000
37-
fmt = small_formatting if value < base else formatting
3841

3942
if value == 1 and not gnu:
40-
return f"{1:{fmt}} Byte"
43+
return f"{1:{small_formatting}} Byte"
4144
if value < base and not gnu:
42-
return f"{value:{fmt}} Bytes"
45+
return f"{value:{small_formatting}} Bytes"
4346
if value < base and gnu:
44-
return f"{value:{fmt}}B"
47+
return f"{value:{small_formatting}}B"
4548

4649
byte_size = float(value)
4750
suffix = ""
4851
for i, suffix in enumerate(suffixes):
4952
unit = base ** (i + 2)
5053
if byte_size < unit:
51-
return f"{base * byte_size / unit:{fmt}}{suffix}"
52-
return f"{base * byte_size / unit:{fmt}}{suffix}"
54+
return f"{base * byte_size / unit:{formatting}}{suffix}"
55+
return f"{base * byte_size / unit:{formatting}}{suffix}"

0 commit comments

Comments
 (0)