Flexparser for Typed Parsing
Flexparser is a Python library that enables parsing of string-based data into complex Python objects using type hints. Inspired by Pydantic, it leverages `typing` module annotations to define target data structures. Currently at version 0.4, its release cadence is infrequent but maintained.
Warnings
- breaking As a pre-1.0 library, `flexparser`'s API is subject to change without prior notice across minor versions. Features might be renamed, modified, or removed.
- gotcha Flexparser relies heavily on runtime type introspection for parsing. Complex or highly nested custom types, or advanced `typing` features (e.g., `TypedDict`, `NewType`) might require explicit parser registration or might not be fully supported without specific extensions.
- gotcha Error messages for malformed input might sometimes be generic or not pinpoint the exact line/token causing the issue, making debugging complex parsing failures challenging.
Install
-
pip install flexparser
Imports
- parse_string
from flexparser import parse_string
- parse_object
from flexparser import parse_object
Quickstart
from flexparser import parse_string
from typing import Dict, List, Union, Tuple
# Define the target structure using type hints.
# Flexparser will use these annotations at runtime to understand
# how to parse the input string.
def parse_config_data(data_str: str) -> Dict[str, Union[str, int, float, bool, List[str], Tuple[int, int]]]:
"""
Parses a string into a dictionary based on the return type hints.
The function body itself is not executed for parsing;
only its annotations are used by flexparser.
"""
pass
config_string = """
name: Alice
age: 30
city: New York
tags: python, parsing
location: (10, 20)
is_active: true
score: 98.5
"""
# Parse the string using the return annotation of 'parse_config_data'
parsed_data = parse_string(config_string, target_type=parse_config_data.__annotations__['return'])
print("Parsed Data:", parsed_data)
print("Type of name:", type(parsed_data.get('name')))
print("Type of age:", type(parsed_data.get('age')))
print("Type of tags:", type(parsed_data.get('tags')))
print("Type of location:", type(parsed_data.get('location')))
print("Type of is_active:", type(parsed_data.get('is_active')))