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.6.tar.gz
(8.9 kB
view details)
Built Distribution
strto-0.1.6-py3-none-any.whl
(7.1 kB
view details)
File details
Details for the file strto-0.1.6.tar.gz
.
File metadata
- Download URL: strto-0.1.6.tar.gz
- Upload date:
- Size: 8.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 213c0694ca75731945835665151ea607686478cb6b7cf7f2b3080f2a61ddb60f |
|
MD5 | 422661663d9246f07cb427abc6839ca1 |
|
BLAKE2b-256 | de6069d711efdaeba4a2b15033f2d4ffe590b885b25102e269135b241f3cf985 |
File details
Details for the file strto-0.1.6-py3-none-any.whl
.
File metadata
- Download URL: strto-0.1.6-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.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5b140e3cdd6f98e0bb2e13c7dc64d255722a756ba8226afd61425a14cd7c9b54 |
|
MD5 | 36c77a945036dfb3337db81501f049f8 |
|
BLAKE2b-256 | 3690313bcba6024fe56f2181926f42b370c6c894b9f0ec98d232f26a17e57277 |