Classes

ParseResult

class formatparse.ParseResult(*args, **kwargs)

Stub for ParseResult (extension not built).

__init__(*args, **kwargs)

Accept construction like the real Rust-backed type (docs build stub).

FormatParser

class formatparse.FormatParser(*args, **kwargs)

Stub for FormatParser (extension not built).

__init__(*args, **kwargs)

Accept construction like the real Rust-backed type (docs build stub).

BidirectionalPattern

class formatparse.BidirectionalPattern(pattern, extra_types=None)[source]

A bidirectional pattern that can parse and format strings.

Enables round-trip parsing: parse → modify → format back, with built-in validation. This class combines parsing and formatting capabilities, allowing you to parse a string, modify the extracted values, and format them back while maintaining the original format constraints.

Parameters:
  • pattern (str) – Format string pattern (e.g., "{name:>10}: {value:05d}")

  • extra_types (dict, optional) – Optional dictionary of custom type converters

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> result = formatter.parse("      John: 00042")
>>> result.named['name']
'John'
>>> result.named['value']
42
>>> result.format()
'      John: 00042'
>>> result.named['value'] = 100
>>> result.format()
'      John: 00100'
__init__(pattern, extra_types=None)[source]

Initialize a bidirectional pattern.

Parameters:
  • pattern (str) – Format string pattern (e.g., "{name:>10}: {value:05d}")

  • extra_types (dict, optional) – Optional dictionary of custom type converters

parse(string, case_sensitive=False, evaluate_result=True)[source]

Parse a string and return BidirectionalResult.

Parameters:
  • string (str) – String to parse

  • case_sensitive (bool) – Whether matching is case-sensitive (default: False)

  • evaluate_result (bool) – Whether to evaluate result (convert types) (default: True)

Returns:

BidirectionalResult if match found, None otherwise

Return type:

BidirectionalResult or None

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> result = formatter.parse("      John: 00042")
>>> result.named['name']
'John'
>>> result.named['value']
42
format(values)[source]

Format values back into the pattern.

Formats the provided values according to the pattern specification, maintaining format constraints like width, precision, and alignment.

Parameters:

values (dict, tuple, or ParseResult) – Dictionary (for named fields), tuple (for positional), or ParseResult

Returns:

Formatted string matching the pattern

Return type:

str

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> formatter.format({"name": "John", "value": 42})
'      John: 00042'
>>> formatter.format(("John", 42))  # Positional fields
'      John: 00042'
validate(values)[source]

Validate values against format constraints.

Parameters:

values (Union[dict, tuple, ParseResult]) – Dict (for named fields), tuple (for positional), or ParseResult

Return type:

Tuple[bool, List[str]]

Returns:

Tuple of (is_valid, list_of_errors)

BidirectionalResult

class formatparse.BidirectionalResult(pattern, result)[source]

Result from BidirectionalPattern.parse() that allows modification and formatting.

Stores parsed values in a mutable format and provides methods to format back and validate against the original pattern constraints. Unlike ParseResult, this class allows you to modify the extracted values and format them back while maintaining the original format constraints.

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> result = formatter.parse("      John: 00042")
>>> result.named['value'] = 100
>>> result.format()
'      John: 00100'
>>> result.validate()
(True, [])
__init__(pattern, result)[source]

Initialize a bidirectional result.

Parameters:
property named: Dict[str, Any]

Mutable named fields dictionary.

Returns:

Dictionary of named fields (can be modified)

Return type:

Dict[str, Any]

Example:

>>> formatter = BidirectionalPattern("{name}: {age:d}")
>>> result = formatter.parse("Alice: 30")
>>> result.named['age'] = 31
>>> result.format()
'Alice: 31'
property fixed: List[Any]

Mutable fixed (positional) fields list.

Returns:

List of positional fields (can be modified)

Return type:

List[Any]

Example:

>>> formatter = BidirectionalPattern("{}, {}")
>>> result = formatter.parse("Hello, World")
>>> result.fixed[1] = "Python"
>>> result.format()
'Hello, Python'
format()[source]

Format values back using the pattern.

Formats the current (potentially modified) values according to the original pattern specification.

Returns:

Formatted string matching the original pattern

Return type:

str

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> result = formatter.parse("      John: 00042")
>>> result.named['value'] = 100
>>> result.format()
'      John: 00100'
validate()[source]

Validate current values against format constraints.

Checks if the current (potentially modified) values conform to the pattern’s constraints (type, width, precision).

Returns:

Tuple of (is_valid, list_of_errors)

Return type:

Tuple[bool, List[str]]

Example:

>>> formatter = BidirectionalPattern("{name:>10}: {value:05d}")
>>> result = formatter.parse("      John: 00042")
>>> result.validate()
(True, [])
>>> result.named['value'] = "not a number"
>>> is_valid, errors = result.validate()
>>> is_valid
False
>>> len(errors) > 0
True
__repr__()[source]

String representation

Return type:

str

FixedTzOffset

class formatparse.FixedTzOffset(offset_minutes, name)[source]

Fixed timezone offset compatible with datetime.tzinfo.

This class provides a fixed timezone offset implementation that is compatible with Python’s datetime.tzinfo interface. It’s used internally for datetime parsing when timezone information is present.

Parameters:
  • offset_minutes (int) – Timezone offset in minutes from UTC

  • name (str) – Timezone name (e.g., “EST”, “PST”)

Example:

>>> from formatparse import FixedTzOffset
>>> from datetime import datetime
>>> tz = FixedTzOffset(300, "EST")  # UTC-5
>>> dt = datetime(2024, 1, 1, 12, 0, tzinfo=tz)
>>> tz.utcoffset(dt)
datetime.timedelta(seconds=18000)
>>> tz.dst(dt) is None
True
>>> tz.tzname(dt)
'EST'
__init__(offset_minutes, name)[source]

Initialize a fixed timezone offset.

Parameters:
  • offset_minutes (int) – Timezone offset in minutes from UTC

  • name (str) – Timezone name (e.g., “EST”, “PST”)

utcoffset(dt)[source]

Return the timezone offset from UTC.

Parameters:

dt (datetime.datetime) – Datetime object (unused, kept for compatibility)

Returns:

Timezone offset as timedelta

Return type:

datetime.timedelta

dst(dt)[source]

Return daylight saving time adjustment (always None for fixed offsets).

Parameters:

dt (datetime.datetime) – Datetime object (unused, kept for compatibility)

Returns:

Always None for fixed timezone offsets

Return type:

None

tzname(dt)[source]

Return the timezone name.

Parameters:

dt (datetime.datetime) – Datetime object (unused, kept for compatibility)

Returns:

Timezone name

Return type:

str