parse-size
parse-size

how parse-size fits in

Install

consolepip install parse-size

Use

pythonfrom parse_size import SizeParseError, format_size, parse_size

parse_size("10 MB")                    # 10_000_000
parse_size("10MiB")                    # 10_485_760
parse_size("2 gigabytes")              # 2_000_000_000
parse_size("5", default_unit="MiB")    # 5_242_880
parse_size("-1 MB", allow_negative=True)

format_size(1_500_000)                       # '1.5 MB'
format_size(1_234_567, precision=0)          # '1 MB'  (rounded, not truncated)
format_size(1_500_000, space=False)          # '1.5MB'
format_size(1_234_567, precision=None)       # '1.234567 MB'  (exact)
format_size(3 * 1024**3, binary=True)        # '3 GiB'

A common argparse pair:

pythonparser.add_argument("--max-size", type=parse_size, default="10 MB")
parser.add_argument("--pretty", action="store_true")
# --max-size 1.5GiB  →  1610612736

Rules

suffix factor suffix factor
-------------------------
B1KiB1024
KB1000MiB1024²
MB1000²GiB1024³
GB1000³TiB1024⁴
TB1000⁴PiB1024⁵
PB1000⁵

Limits

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.