Flexparser for Typed Parsing

0.4 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `flexparser.parse_string` to parse a YAML-like string into a Python dictionary, leveraging type hints for schema definition. The `target_type` argument tells `flexparser` what structure to expect, which it infers from the return annotation of `parse_config_data`.

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')))

view raw JSON →