Type-guided parsing library for converting strings to Python objects
Project description
strto
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
Add custom parser
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
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
strto-0.1.4.tar.gz
(8.9 kB
view details)
Built Distribution
strto-0.1.4-py3-none-any.whl
(7.1 kB
view details)
File details
Details for the file strto-0.1.4.tar.gz
.
File metadata
- Download URL: strto-0.1.4.tar.gz
- Upload date:
- Size: 8.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 964adfb7633a2adfdbf8a47be724f35ef731b1103765adf2352bda0582d2d821 |
|
MD5 | dbcadfaba077494278f30f8d3f530740 |
|
BLAKE2b-256 | 132b024bc9d6ee0fd64e7f81bb0a5409576102091c09ed30e2298fb7ade5771d |
File details
Details for the file strto-0.1.4-py3-none-any.whl
.
File metadata
- Download URL: strto-0.1.4-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0ea5614822576b9192e049b1340cadf68b35729ec7699aa66c25e54a0ddfc484 |
|
MD5 | fde2da14e18b66db6c14c91456197adb |
|
BLAKE2b-256 | f669aeaeea972d475f93f9f8d50879f88e4ab19ba267c082c52a36fd33029169 |