Parse-Type
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
- gotcha The `parse-type` library embeds its own copy of the `parse` module (e.g., `parse_type.parse`). This can lead to confusion or potential version conflicts if you also have the `parse` library installed externally from PyPI. While `parse-type` aims for compatibility, explicit imports of `parse` might pick up the external version instead of the embedded one.
- deprecated Although `parse-type` specifies Python 2.7 support in its `requires_python` metadata, Python 2.7 is end-of-life and no longer receives security updates. Using `parse-type` with Python 2.7 is strongly discouraged.
- gotcha Releases of `parse-type` have included fixes related to upstream behavior changes in the `parse` module (e.g., `parse v1.19.1` breaking some behavior). This highlights that the interaction with `parse` can be subtle.
Install
-
pip install parse-type
Imports
- TypeBuilder
from parse_type import TypeBuilder
- parse
from parse import parse
Quickstart
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.")