Skip to main content

strto

Tests PyPI version Supported versions Downloads license

strto is a Python library for parsing strings into Python objects based on types and type annotations.

Installation

From PyPi

pip install strto

From source

pip install git+https://github.com/zigai/strto.git

Examples

>>> from strto import get_parser
>>> parser = get_parser()

>>> parser.parse("5", int)
5
>>> parser.parse("1.5", int | float)
1.5
>>> parser.parse("1,2,3,4,5", list[int])
[1, 2, 3, 4, 5]
>>> parser.parse('{"a":1,"b":2,"c":3}', dict[str, int])
{'a': 1, 'b': 2, 'c': 3}

import datetime
>>> parser.parse("2022.07.19", datetime.date)
datetime.date(2022, 7, 19)

>>> parser.parse("0:5:1", range)
range(0, 5, 1)

>>> import enum
>>> class Color(enum.Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
>>> parser.parse("RED", Color)
Color.RED

Automatic model parsing (dataclasses and pydantic v2)

strto can parse dataclasses and pydantic v2 models from JSON, files, or key/value strings:

from dataclasses import dataclass
from strto import get_parser


@dataclass
class NetworkAddress:
    host: str
    port: int


parser = get_parser()

parser.parse('{"host":"localhost","port":5432}', NetworkAddress)
parser.parse("host=localhost port=5432", NetworkAddress)
parser.parse("@addr.yaml", NetworkAddress)

Nested models via dotted keys (or nested JSON):

from dataclasses import dataclass


@dataclass
class NetworkAddress:
    host: str
    port: int


@dataclass
class ApplicationConfig:
    debug: bool = False
    network: NetworkAddress | None = None


parser.parse(
    "debug=true network.host=db network.port=5433",
    ApplicationConfig,
)

Notes:

  • Key/value parsing supports dotted keys for nested objects.
  • Use JSON arrays/objects for complex values (e.g., lists of objects).
  • Pydantic support requires pydantic v2 to be installed.

Optional: enable parsing for any class by inspecting __init__ with objinspect:

from strto import get_parser

parser = get_parser(allow_class_init=True)

Custom parser for alternative string formats

If you want a non-standard string format (e.g., host:port), register a custom parser to override the default model parsing for that type.

from dataclasses import dataclass
from strto import ParserBase, get_parser


@dataclass
class NetworkAddress:
    host: str
    port: int


class NetworkAddressParser(ParserBase):
    def parse(self, value: str) -> NetworkAddress:
        host, port = value.rsplit(":")
        return NetworkAddress(host=host, port=int(port))


parser = get_parser()
parser.add(NetworkAddress, NetworkAddressParser())
result = parser.parse("example.com:8080", NetworkAddress)
print(result)  # NetworkAddress(host='example.com', port=8080)


# You can also use a function
def parse_network_address(value: str) -> NetworkAddress:
    host, port = value.rsplit(":")
    return NetworkAddress(host=host, port=int(port))


parser = get_parser()
parser.add(NetworkAddress, parse_network_address)
result = parser.parse("example.com:8080", NetworkAddress)
print(result)  # NetworkAddress(host='example.com', port=8080)

License

MIT License

Metadata

Release files for strto 0.2.10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for strto 0.2.10
File Size Uploaded Provenance
strto-0.2.10.tar.gz 16.0 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for strto 0.2.10
File Interpreter ABI Platform
strto-0.2.10-py3-none-any.whl Python 3 none any Details

Total release size: 31.7 kB

Release files / strto-0.2.10.tar.gz

Download URL strto-0.2.10.tar.gz
Size 16.0 kB
Tags Source
SHA-256 checksum
How to use checksums
4bb83537977c03280a68e79789f1038e850bae701210d9a7a1f1a4497811a15a
BLAKE2b-256 checksum
How to use checksums
f4ca0ceedf7d2a67bc155037c58886fd5cac0ac467d7aca61a1bdca1d05196de
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / strto-0.2.10-py3-none-any.whl

Download URL strto-0.2.10-py3-none-any.whl
Size 15.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1a8788814f334ed6921fd5b49945fc0fceb4293839f99b50e88c581df700c132
BLAKE2b-256 checksum
How to use checksums
4de7578456d3a68908d60ac2db8607287794e42631f6ee136b573593db44c2c1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for strto 0.2.10

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page