structured_data.match

Utilities for destructuring values using matchables and match targets.

Given a value to destructure, called value:

  • Construct a matchable: matchable = Matchable(value)
  • The matchable is initially falsy, but it will become truthy if it is passed a match target that matches value: assert matchable(some_pattern_that_matches) (Matchable returns itself from the call, so you can put the calls in an if-elif block, and only make a given call at most once.)
  • When the matchable is truthy, it can be indexed to access bindings created by the target.
class structured_data.match.AttrPattern[source]

A matcher that destructures an object using attribute access.

The AttrPattern constructor takes keyword arguments. Each name-value pair is the name of an attribute, and a matcher to apply to that attribute.

Attributes are checked in the order they were passed.

destructure(value) → Union[Tuple[()], Tuple[Any, Any]][source]

Return a tuple of sub-values to check.

If self is empty, return no values from self or the target.

Special-case matching against another AttrPattern as follows: Confirm that the target isn’t smaller than self, then Extract the first match from the target’s match_dict, and Return the smaller value, and the first match’s value. (This works as desired when value is self, but all other cases where isinstance(value, AttrPattern) are unspecified.)

By default, it takes the first match from the match_dict, and returns the original value, and the result of calling getattr with the target and the match’s key.

match_dict

Return the dict of matches to check.

class structured_data.match.Bind[source]

A wrapper that adds additional bindings to a successful match.

The Bind constructor takes a single required argument, and any number of keyword arguments. The required argument is a matcher. When matching, if the match succeeds, the Bind instance adds bindings corresponding to its keyword arguments.

First, the matcher is checked, then the bindings are added in the order they were passed.

bindings

Return the bindings to add to the match.

destructure(value)[source]

Return a list of sub-values to check.

If value is self, return all of the bindings, and the structure.

Otherwise, return the corresponding bound values, followed by the original value.

structure

Return the structure to match against.

class structured_data.match.DictPattern[source]

A matcher that destructures a dictionary by key.

The DictPattern constructor takes a required argument, a dictionary where the keys are keys to check, and the values are matchers to apply. It also takes an optional keyword argument, “exhaustive”, which defaults to False. If “exhaustive” is True, then the match requires that the matched dictionary has no keys not in the DictPattern. Otherwise, “extra” keys are ignored.

Keys are checked in iteration order.

destructure(value) → Union[Tuple[()], Tuple[Any, Any]][source]

Return a tuple of sub-values to check.

If self is exhaustive and the lengths don’t match, fail.

If self is empty, return no values from self or the target.

Special-case matching against another DictPattern as follows: Confirm that the target isn’t smaller than self, then Extract the first match from the target’s match_dict, and Return the smaller value, and the first match’s value. Note that the returned DictPattern is never exhaustive; the exhaustiveness check is accomplished by asserting that the lengths start out the same, and that every key in self is present in value. (This works as desired when value is self, but all other cases where isinstance(value, DictPattern) are unspecified.)

By default, it takes the first match from the match_dict, and returns the original value, and the result of indexing the target with the match’s key.

exhaustive

Return whether the target must of the exact keys as self.

exhaustive_length_must_match(value: Sized)[source]

If the match is exhaustive and the lengths differ, fail.

match_dict

Return the dict of matches to check.

class structured_data.match.MatchDict[source]

A MutableMapping that allows for retrieval into structures.

The actual keys in the mapping must be string values. Most of the mapping methods will only operate on or yield string keys. The exception is subscription: the “key” in subscription can be a structure made of tuples and dicts. For example, md["a", "b"] == (md["a"], md["b"]), and md[{1: "a"}] == {1: md["a"]}. The typical use of this will be to extract many match values at once, as in a, b, c == md["a", "b", "c"].

The behavior of most of the pre-defined MutableMapping methods is currently neither tested nor guaranteed.

class structured_data.match.Matchable(value: Any)[source]

Given a value, attempt to match against a target.

The truthiness of Matchable values varies on whether they have bindings associated with them. They are truthy exactly when they have bindings.

Matchable values provide two basic forms of syntactic sugar. m_able(target) is equivalent to m_able.match(target), and m_able[k] will return m_able.matches[k] if the Matchable is truthy, and raise a ValueError otherwise.

match(target) → structured_data._match.matchable.Matchable[source]

Match against target, generating a set of bindings.

class structured_data.match.Pattern[source]

A matcher that binds a value to a name.

A Pattern can be indexed with another matcher to produce an AsPattern. When matched with a value, an AsPattern both binds the value to the name, and uses the matcher to match the value, thereby constraining it to have a particular shape, and possibly introducing further bindings.

name

Return the name of the matcher.

class structured_data.match.Property(func=None, fset=None, fdel=None, doc=None, *args, **kwargs)[source]

Decorator with value-based dispatch. Acts as a property.

delete_when(instance)[source]

Add a binding to the deleter.

deleter(deleter)[source]

Return a copy of self with the deleter replaced.

get_when(instance)[source]

Add a binding to the getter.

getter(getter)[source]

Return a copy of self with the getter replaced.

set_when(instance, value)[source]

Add a binding to the setter.

setter(setter)[source]

Return a copy of self with the setter replaced.

structured_data.match.decorate_in_order(*args)[source]

Apply decorators in the order they’re passed to the function.

structured_data.match.function(_func=None, *, positional_until=0)[source]

Convert a function to dispatch by value.

The original function is not called when the dispatch function is invoked.

structured_data.match.names(target) → List[str][source]

Return every name bound by a target.