Parse-Type

0.6.6 · active · verified Thu Apr 09

Parse-Type is a Python library that simplifies the creation of custom type definitions for the `parse` module. It extends `parse`'s capabilities by allowing users to easily integrate enums, regular expressions, and custom functions as parsable types. The current version is 0.6.6. Releases are primarily driven by updates to the underlying `parse` module and general maintenance, leading to an irregular but consistent cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a custom type using an Enum and integrate it into a `parse` pattern. It uses `TypeBuilder.with_enum` to prepare the custom type, then passes it to the `parse` function.

from enum import Enum
from parse import parse
from parse_type import TypeBuilder

# 1. Define an Enum to be used as a custom type
class ColorEnum(Enum):
    red = 1
    green = 2
    blue = 3

# 2. Create a TypeBuilder instance, integrating the Enum
#    TypeBuilder can also create types from regex or functions.
parse_types = TypeBuilder.with_enum(ColorEnum)

# 3. Define a parse pattern using the custom type
pattern = "The color is {color:Color}"
text = "The color is blue"

# 4. Use the parse function, passing the custom type definitions
#    The key 'Color' in the dict corresponds to the type name in the pattern.
result = parse(pattern, text, dict(Color=parse_types.Color))

if result:
    print(f"Successfully parsed! Color: {result['color']}")
    print(f"Type of parsed color: {type(result['color'])}")
    assert result['color'] is ColorEnum.blue
    print("Assertion successful: Parsed value matches Enum member.")
else:
    print("Parsing failed.")

view raw JSON →