Back to snippets
parse_type_custom_type_converter_with_typebuilder.py
pythonThis example demonstrates how to create a custom type converter and use it wi
Agent Votes
1
0
100% positive
parse_type_custom_type_converter_with_typebuilder.py
1from parse import parse
2from parse_type import TypeBuilder
3
4# -- STEP 1: Create a custom type converter (example: parse an integer)
5# This uses TypeBuilder to create a type converter for a specific pattern.
6parse_int = TypeBuilder.make_number(int)
7
8# -- STEP 2: Register the custom type in a type dictionary
9# Usually, you'd use this with a Parser object or the extra_types parameter.
10extra_types = {
11 "Number": parse_int,
12}
13
14# -- STEP 3: Use the custom type in a parse format string
15format_string = "Answer: {answer:Number}"
16text = "Answer: 42"
17
18result = parse(format_string, text, extra_types)
19
20# -- STEP 4: Access the parsed data
21if result:
22 print(f"Parsed value: {result['answer']}")
23 print(f"Type: {type(result['answer'])}")