docutils.statemachine module
A finite state machine specialized for regular-expression-based text filters, this module defines the following classes:
StateMachine, a state machine
State, a state superclass
StateMachineWS, a whitespace-sensitive version of StateMachine
StateWS, a state superclass for use with StateMachineWS
SearchStateMachine, uses re.search() instead of re.match()
SearchStateMachineWS, uses re.search() instead of re.match()
ViewList, extends standard Python lists.
StringList, string-specific ViewList.
Exception classes:
StateMachineError
UnknownStateError
DuplicateStateError
UnknownTransitionError
DuplicateTransitionError
TransitionPatternNotFound
TransitionMethodNotFound
UnexpectedIndentationError
TransitionCorrection: Raised to switch to another transition.
StateCorrection: Raised to switch to another state & transition.
Functions:
string2lines(): split a multi-line string into a list of one-line strings
How To Use This Module
(See the individual classes, methods, and attributes for details.)
Import it:
import statemachine
orfrom statemachine import ...
. You will also need toimport re
.Derive a subclass of State (or StateWS) for each state in your state machine:
class MyState(statemachine.State):
Within the state’s class definition:
Include a pattern for each transition, in State.patterns:
patterns = {'atransition': r'pattern', ...}
Include a list of initial transitions to be set up automatically, in State.initial_transitions:
initial_transitions = ['atransition', ...]
Define a method for each transition, with the same name as the transition pattern:
def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered
Transition methods may raise an EOFError to cut processing short.
You may wish to override the State.bof() and/or State.eof() implicit transition methods, which handle the beginning- and end-of-file.
In order to handle nested processing, you may wish to override the attributes State.nested_sm and/or State.nested_sm_kwargs.
If you are using StateWS as a base class, in order to handle nested indented blocks, you may wish to:
override the attributes StateWS.indent_sm, StateWS.indent_sm_kwargs, StateWS.known_indent_sm, and/or StateWS.known_indent_sm_kwargs;
override the StateWS.blank() method; and/or
override or extend the StateWS.indent(), StateWS.known_indent(), and/or StateWS.firstknown_indent() methods.
Create a state machine object:
sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState')
Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called ‘inputfile’:
with open('inputfile', encoding='utf-8') as fp: input_string = fp.read() input_lines = statemachine.string2lines(input_string)
Run the state machine on the input text and collect the results, a list:
results = sm.run(input_lines)
Remove any lingering circular references:
sm.unlink()
- class StateMachine(state_classes, initial_state, debug=False)[source]
Bases:
object
A finite state machine for text filters using regular expressions.
The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the State class. Transitions consist of regular expression patterns and transition methods, and are defined in each state.
The state machine is started with the run() method, which returns the results of processing in a list.
- __init__(state_classes, initial_state, debug=False)[source]
Initialize a StateMachine object; add state objects.
Parameters:
state_classes: a list of State (sub)classes.
initial_state: a string, the class name of the initial state.
debug: a boolean; produce verbose output if true (nonzero).
- input_lines
StringList of input lines (without newlines). Filled by self.run().
- input_offset
Offset of self.input_lines from the beginning of the file.
- line
Current input line.
- line_offset
Current input line offset from beginning of self.input_lines.
- debug
Debugging mode on/off.
- initial_state
The name of the initial state (key to self.states).
- current_state
The name of the current state (key to self.states).
- states
State_object}.
- Type:
Mapping of {state_name
- observers
List of bound methods or functions to call whenever the current line changes. Observers are called with one argument,
self
. Cleared at the end of run().
- run(input_lines, input_offset=0, context=None, input_source=None, initial_state=None)[source]
Run the state machine on input_lines. Return results (a list).
Reset self.line_offset and self.current_state. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results.
Parameters:
input_lines: a list of strings without newlines, or StringList.
input_offset: the line offset of input_lines from the beginning of the file.
context: application-specific storage.
input_source: name or path of source of input_lines.
initial_state: name of initial state.
- get_state(next_state=None)[source]
Return current state object; set it first if next_state given.
Parameter next_state: a string, the name of the next state.
Exception: UnknownStateError raised if next_state unknown.
- get_source_and_line(lineno=None)[source]
Return (source, line) tuple for current or given line number.
Looks up the source and line number in the self.input_lines StringList instance to count for included source files.
If the optional argument lineno is given, convert it from an absolute line number to the corresponding (source, line) pair.
- get_text_block(flush_left=False)[source]
Return a contiguous block of text.
If flush_left is true, raise UnexpectedIndentationError if an indented line is encountered before the text block ends (with a blank line).
- check_line(context, state, transitions=None)[source]
Examine one line of input for a transition match & execute its method.
Parameters:
context: application-dependent storage.
state: a State object, the current state.
transitions: an optional ordered list of transition names to try, instead of
state.transition_order
.
Return the values returned by the transition method:
context: possibly modified from the parameter context;
next state name (State subclass name);
the result output of the transition, a list.
When there is no match,
state.no_match()
is called and its return value is returned.
- add_state(state_class)[source]
Initialize & add a state_class (State subclass) object.
Exception: DuplicateStateError raised if state_class was already added.
- class State(state_machine, debug=False)[source]
Bases:
object
State superclass. Contains a list of transitions, and transition methods.
Transition methods all have the same signature. They take 3 parameters:
An re match object.
match.string
contains the matched input line,match.start()
gives the start index of the match, andmatch.end()
gives the end index.A context object, whose meaning is application-defined (initial value
None
). It can be used to store any information required by the state machine, and the returned context is passed on to the next transition method unchanged.The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary.
Transition methods all return a 3-tuple:
A context object, as (potentially) modified by the transition method.
The next state name (a return value of
None
means no state change).The processing result, a list, which is accumulated by the state machine.
Transition methods may raise an EOFError to cut processing short.
There are two implicit transitions, and corresponding transition methods are defined: bof() handles the beginning-of-file, and eof() handles the end-of-file. These methods have non-standard signatures and return values. bof() returns the initial context and results, and may be used to return a header string, or do any other processing needed. eof() should handle any remaining context and wrap things up; it returns the final processing result.
Typical applications need only subclass State (or a subclass), set the patterns and initial_transitions class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions.
- patterns = None
pattern} mapping, used by make_transition(). Each pattern may be a string or a compiled re pattern. Override in subclasses.
- Type:
{Name
- initial_transitions = None
A list of transitions to initialize when a State is instantiated. Each entry is either a transition name string, or a (transition name, next state name) pair. See make_transitions(). Override in subclasses.
- __init__(state_machine, debug=False)[source]
Initialize a State object; make & add initial transitions.
Parameters:
statemachine: the controlling StateMachine object.
debug: a boolean; produce verbose output if true.
- transition_order
A list of transition names in search order.
- transitions
A mapping of transition names to 3-tuples containing (compiled_pattern, transition_method, next_state_name). Initialized as an instance attribute dynamically (instead of as a class attribute) because it may make forward references to patterns and methods in this or other classes.
- state_machine
A reference to the controlling StateMachine object.
- debug
Debugging mode on/off.
- nested_sm = None
The StateMachine class for handling nested processing.
If left as
None
, nested_sm defaults to the class of the state’s controlling state machine. Override it in subclasses to avoid the default.
- nested_sm_kwargs = None
Keyword arguments dictionary, passed to the nested_sm constructor.
Two keys must have entries in the dictionary:
Key ‘state_classes’ must be set to a list of State classes.
Key ‘initial_state’ must be set to the name of the initial state class.
If nested_sm_kwargs is left as
None
, ‘state_classes’ defaults to the class of the current state, and ‘initial_state’ defaults to the name of the class of the current state. Override in subclasses to avoid the defaults.
- runtime_init()[source]
Initialize this State before running the state machine; called from self.state_machine.run().
- add_transitions(names, transitions)[source]
Add a list of transitions to the start of the transition list.
Parameters:
names: a list of transition names.
transitions: a mapping of names to transition tuples.
Exceptions: DuplicateTransitionError, UnknownTransitionError.
- add_transition(name, transition)[source]
Add a transition to the start of the transition list.
Parameter transition: a ready-made transition 3-tuple.
Exception: DuplicateTransitionError.
- make_transition(name, next_state=None)[source]
Make & return a transition tuple based on name.
This is a convenience function to simplify transition creation.
Parameters:
name: a string, the name of the transition pattern & method. This State object must have a method called ‘name’, and a dictionary self.patterns containing a key ‘name’.
next_state: a string, the name of the next State object for this transition. A value of
None
(or absent) implies no state change (i.e., continue with the same state).
Exceptions: TransitionPatternNotFound, TransitionMethodNotFound.
- make_transitions(name_list)[source]
Return a list of transition names and a transition mapping.
Parameter name_list: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name).
- no_match(context, transitions)[source]
Called when there is no match from StateMachine.check_line().
Return the same values returned by transition methods:
context: unchanged;
next state name:
None
;empty result list.
Override in subclasses to catch this event.
- bof(context)[source]
Handle beginning-of-file. Return unchanged context, empty result.
Override in subclasses.
Parameter context: application-defined storage.
- class StateMachineWS(state_classes, initial_state, debug=False)[source]
Bases:
StateMachine
StateMachine subclass specialized for whitespace recognition.
There are three methods provided for extracting indented text blocks:
get_indented(): use when the indent is unknown.
get_known_indented(): use when the indent is known for all lines.
get_first_known_indented(): use when only the first line’s indent is known.
- get_indented(until_blank=False, strip_indent=True)[source]
Return a block of indented lines of text, and info.
Extract an indented block where the indent is unknown for all lines.
- Parameters:
until_blank: Stop collecting at the first blank line if true.
strip_indent: Strip common leading indent if true (default).
- Return:
the indented block (a list of lines of text),
its indent,
its first line offset from BOF, and
whether or not it finished with a blank line.
- get_known_indented(indent, until_blank=False, strip_indent=True)[source]
Return an indented block and info.
Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least indent indentation (which must be whitespace, except for the first line).
- Parameters:
indent: The number of indent columns/characters.
until_blank: Stop collecting at the first blank line if true.
strip_indent: Strip indent characters of indentation if true (default).
- Return:
the indented block,
its first line offset from BOF, and
whether or not it finished with a blank line.
- get_first_known_indented(indent, until_blank=False, strip_indent=True, strip_top=True)[source]
Return an indented block and info.
Extract an indented block where the indent is known for the first line and unknown for all other lines.
- Parameters:
indent: The first line’s indent (# of columns/characters).
until_blank: Stop collecting at the first blank line if true (1).
strip_indent: Strip indent characters of indentation if true (1, default).
strip_top: Strip blank lines from the beginning of the block.
- Return:
the indented block,
its indent,
its first line offset from BOF, and
whether or not it finished with a blank line.
- class StateWS(state_machine, debug=False)[source]
Bases:
State
State superclass specialized for whitespace (blank lines & indents).
Use this class with StateMachineWS. The transitions ‘blank’ (for blank lines) and ‘indent’ (for indented text blocks) are added automatically, before any other transitions. The transition method blank() handles blank lines and indent() handles nested indented blocks. Indented blocks trigger a new state machine to be created by indent() and run. The class of the state machine to be created is in indent_sm, and the constructor keyword arguments are in the dictionary indent_sm_kwargs.
The methods known_indent() and firstknown_indent() are provided for indented blocks where the indent (all lines’ and first line’s only, respectively) is known to the transition method, along with the attributes known_indent_sm and known_indent_sm_kwargs. Neither transition method is triggered automatically.
- ws_patterns = {'blank': re.compile(' *$'), 'indent': re.compile(' +')}
Patterns for default whitespace transitions. May be overridden in subclasses.
- ws_initial_transitions = ('blank', 'indent')
Default initial whitespace transitions, added before those listed in State.initial_transitions. May be overridden in subclasses.
- __init__(state_machine, debug=False)[source]
Initialize a StateSM object; extends State.__init__().
Check for indent state machine attributes, set defaults if not set.
- indent_sm = None
The StateMachine class handling indented text blocks.
If left as
None
, indent_sm defaults to the value of State.nested_sm. Override it in subclasses to avoid the default.
- indent_sm_kwargs = None
Keyword arguments dictionary, passed to the indent_sm constructor.
If left as
None
, indent_sm_kwargs defaults to the value of State.nested_sm_kwargs. Override it in subclasses to avoid the default.
- known_indent_sm = None
The StateMachine class handling known-indented text blocks.
If left as
None
, known_indent_sm defaults to the value of indent_sm. Override it in subclasses to avoid the default.
- known_indent_sm_kwargs = None
Keyword arguments dictionary, passed to the known_indent_sm constructor.
If left as
None
, known_indent_sm_kwargs defaults to the value of indent_sm_kwargs. Override it in subclasses to avoid the default.
- add_initial_transitions()[source]
Add whitespace-specific transitions before those defined in subclass.
Extends State.add_initial_transitions().
- blank(match, context, next_state)[source]
Handle blank lines. Does nothing. Override in subclasses.
- indent(match, context, next_state)[source]
Handle an indented text block. Extend or override in subclasses.
Recursively run the registered state machine for indented blocks (self.indent_sm).
- known_indent(match, context, next_state)[source]
Handle a known-indent text block. Extend or override in subclasses.
Recursively run the registered state machine for known-indent indented blocks (self.known_indent_sm). The indent is the length of the match,
match.end()
.
- first_known_indent(match, context, next_state)[source]
Handle an indented text block (first line’s indent known).
Extend or override in subclasses.
Recursively run the registered state machine for known-indent indented blocks (self.known_indent_sm). The indent is the length of the match,
match.end()
.
- class _SearchOverride[source]
Bases:
object
Mix-in class to override StateMachine regular expression behavior.
Changes regular expression matching, from the default re.match() (succeeds only if the pattern matches at the start of self.line) to re.search() (succeeds if the pattern matches anywhere in self.line). When subclassing a StateMachine, list this class first in the inheritance list of the class definition.
- class SearchStateMachine(state_classes, initial_state, debug=False)[source]
Bases:
_SearchOverride
,StateMachine
StateMachine which uses re.search() instead of re.match().
- class SearchStateMachineWS(state_classes, initial_state, debug=False)[source]
Bases:
_SearchOverride
,StateMachineWS
StateMachineWS which uses re.search() instead of re.match().
- class ViewList(initlist=None, source=None, items=None, parent=None, parent_offset=None)[source]
Bases:
object
List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a “view” (in the SQL sense) of the parent list. Changes to parent lists, however, do not affect active child lists. If a parent list is changed, any active child lists should be recreated.
The start and end of the slice can be trimmed using the trim_start() and trim_end() methods, without affecting the parent list. The link between child and parent lists can be broken by calling disconnect() on the child list.
Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the source(), offset(), and info() methods.
- parent
The parent list.
- parent_offset
Offset of this list from the beginning of the parent list.
- data
The actual list of data, flattened from various sources.
- items
the source of each line and the offset of each line from the beginning of its source.
- Type:
A list of (source, offset) pairs, same length as self.data
- __cast(other)
- class StringList(initlist=None, source=None, items=None, parent=None, parent_offset=None)[source]
Bases:
ViewList
A ViewList with string-specific methods.
- trim_left(length, start=0, end=9223372036854775807)[source]
Trim length characters off the beginning of each item, in-place, from index start to end. No whitespace-checking is done on the trimmed text. Does not affect slice parent.
- get_text_block(start, flush_left=False)[source]
Return a contiguous block of text.
If flush_left is true, raise UnexpectedIndentationError if an indented line is encountered before the text block ends (with a blank line).
- get_indented(start=0, until_blank=False, strip_indent=True, block_indent=None, first_indent=None)[source]
Extract and return a StringList of indented lines of text.
Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless strip_indent is false), and return them. All lines up to but not including the first unindented line will be returned.
- Parameters:
start: The index of the first line to examine.
until_blank: Stop collecting at the first blank line if true.
strip_indent: Strip common leading indent if true (default).
block_indent: The indent of the entire block, if known.
first_indent: The indent of the first line, if known.
- Return:
a StringList of indented lines with minimum indent removed;
the amount of the indent;
a boolean: did the indented block finish with a blank line or EOF?
- exception UnknownStateError[source]
Bases:
StateMachineError
- exception DuplicateStateError[source]
Bases:
StateMachineError
- exception UnknownTransitionError[source]
Bases:
StateMachineError
- exception DuplicateTransitionError[source]
Bases:
StateMachineError
- exception TransitionPatternNotFound[source]
Bases:
StateMachineError
- exception TransitionMethodNotFound[source]
Bases:
StateMachineError
- exception UnexpectedIndentationError[source]
Bases:
StateMachineError
- exception TransitionCorrection[source]
Bases:
Exception
Raise from within a transition method to switch to another transition.
Raise with one argument, the new transition name.
- exception StateCorrection[source]
Bases:
Exception
Raise from within a transition method to switch to another state.
Raise with one or two arguments: new state name, and an optional new transition name.
- string2lines(astring, tab_width=8, convert_whitespace=False, whitespace=re.compile('[\x0b\x0c]'))[source]
Return a list of one-line strings with tabs expanded, no newlines, and trailing whitespace stripped.
Each tab is expanded with between 1 and tab_width spaces, so that the next character’s index becomes a multiple of tab_width (8 by default).
Parameters:
astring: a multi-line string.
tab_width: the number of columns between tab stops.
convert_whitespace: convert form feeds and vertical tabs to spaces?
whitespace: pattern object with the to-be-converted whitespace characters (default [vf]).