Skip to main content

Safe string-to-type coercion — parse_bool, parse_int, parse_float, parse_list, parse_duration

Project description

strcoerce

Safe string-to-type coercion for Python. Zero dependencies.

The problem

import os
DEBUG = bool(os.environ.get("DEBUG", "false"))  # Always True — "false" is a non-empty string

bool("false") is True in Python. This catches experienced developers off guard and is a documented trap with no stdlib fix.

Install

pip install strcoerce

Usage

from strcoerce import parse_bool, parse_int, parse_float, parse_list, parse_duration

# Environment variables
DEBUG  = parse_bool(os.environ.get("DEBUG", "false"))   # False
PORT   = parse_int(os.environ.get("PORT", "8080"))      # 8080
HOSTS  = parse_list(os.environ.get("ALLOWED_HOSTS", ""))  # []

# With defaults
parse_bool("maybe", default=False)  # False — no exception
parse_int("oops",   default=0)      # 0

# Durations
from datetime import timedelta
parse_duration("2h30m")   # timedelta(hours=2, minutes=30)
parse_duration("1w2d")    # timedelta(weeks=1, days=2)

API

parse_bool(s, *, default=<raise>)

Input Result
"1", "true", "yes", "on", "t", "y" True
"0", "false", "no", "off", "f", "n" False
anything else (no default) ParseError
anything else (default given) default

Case-insensitive. Strips surrounding whitespace.

parse_int(s, *, default=<raise>, base=10)

parse_int("42")              # 42
parse_int("0xff", base=16)   # 255
parse_int("bad", default=0)  # 0

parse_float(s, *, default=<raise>)

parse_float("3.14")           # 3.14
parse_float("1e-3")           # 0.001
parse_float("bad", default=0) # 0

parse_list(s, sep=",", *, strip=True)

parse_list("a, b, c")          # ["a", "b", "c"]
parse_list("a|b|c", sep="|")   # ["a", "b", "c"]
parse_list("")                 # []

parse_duration(s)

Parses combinations of Nw Nd Nh Nm Ns (weeks/days/hours/minutes/seconds).

parse_duration("30s")        # timedelta(seconds=30)
parse_duration("5m")         # timedelta(minutes=5)
parse_duration("2h30m")      # timedelta(hours=2, minutes=30)
parse_duration("1w2d3h4m5s") # timedelta(weeks=1, days=2, hours=3, minutes=4, seconds=5)

Error handling

All functions raise ParseError (subclass of ValueError) when input is invalid and no default is given.

from strcoerce import ParseError

try:
    val = parse_bool(user_input)
except ParseError as e:
    print(f"Invalid boolean: {e}")

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

strcoerce-0.1.0.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

strcoerce-0.1.0-py3-none-any.whl (4.7 kB view details)

Uploaded Python 3

File details

Details for the file strcoerce-0.1.0.tar.gz.

File metadata

  • Download URL: strcoerce-0.1.0.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for strcoerce-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f0534ce142830e67c48a7f5e9bfdca1036b58b31a89a381b0a0cd2ab4033b605
MD5 3758e930c40c7ba2ce6f2c3000809389
BLAKE2b-256 22da80c4e0327594b7827ad1a69d59c1583a420388353524d1dd79857fb8ae07

See more details on using hashes here.

Provenance

The following attestation bundles were made for strcoerce-0.1.0.tar.gz:

Publisher: publish.yml on SpinnakerSix/strcoerce

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file strcoerce-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: strcoerce-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 4.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for strcoerce-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 09cb1000911943711d425295a51d3b8798fd16359e6ead82b697f3562224ffbf
MD5 582c482d3ea13686c48693b71a70897c
BLAKE2b-256 40fd5ed834a8d636d63fe48ef1142e35d59bafa452af8927d0f95e0e62844e4a

See more details on using hashes here.

Provenance

The following attestation bundles were made for strcoerce-0.1.0-py3-none-any.whl:

Publisher: publish.yml on SpinnakerSix/strcoerce

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page