Graph-talk Core API

Base Classes

class gt.core.Abstract

Base class for communicative objects.

__call__(*message, **context)

Main method for sending messages to the object.

Parameters:
  • message – list of arbitrary items to be processed one by one.
  • context – key-value description of the message processing context.
Returns:

None for no reaction, False if there is an error, any positive value otherwise.

class gt.core.Access(value)

Bases: gt.core.Abstract

Access provides Abstract-style wrapper to access non-Abstract objects. Each instance has Access.mode to describe the access mode (execute or just return the object as is) and Access.spec to keep the additional information like function arguments specification, etc.

Note

When comparing Access instance with other objects, from Access side, the wrapped value will be used. It means Access(1) will be equal with 1.

CALL = 'call'

Callable object mode.

ABSTRACT = 'abstract'

The callable object is Abstract.

FUNCTION = 'function'

The callable object is function.

VALUE = 'value'

The object is a non-callable (e.g. primitive) value (both mode and spec).

OTHER = 'other'

Unknown mode and spec.

__init__(value)

Creates the new Access instance to wrap the value.

Parameters:value – any object to wrap.
setup()

Inits type information, setting the call proxy method, mode, and spec. Overwrite to support custom types.

Sets the read-only properties:
__call__(*message, **context)

Proxy method to emulate the ‘call’ to the object (execute the function, return the value, etc).

value

Wrapped object.

mode

Access mode (the object is callable or not).

spec

Access spec (call specification, e.g. function argument specification).

static get_access(obj, cache=False)

Gets the Access to the specified object, caches the access instance within the object, if possible.

Parameters:
  • obj – object to wrap into the Access.
  • cache (bool.) – cache the access instance inside the object if True.
Returns:

new Access instance to access the object like an Abstract.

Return type:

Access.

class gt.core.Condition(value, *tags, **options)

Bases: gt.core.Access

Condition is used to check the possibility of the message handling in the specified context. It’s Condition.check() method returns the tuple of (rank, check_result). If the rank is less than 0 it means the condition is not satisfied. The rank shows how relevant this condition is.

The check result is used mostly for regular expressions to analyze its actual match result. Note that Condition.check() method is assigned dynamically basing on the condition object type.

NUMBER = 'number'

Number access spec.

LIST = 'list'

List access spec.

DICT = 'dict'

Dictionary access spec.

STRING = 'string'

String access spec.

REGEX = 'regex'

Regular expression access spec.

BOOLEAN = 'bool'

Boolean access spec.

NO_CHECK = (-1, None)

Returned if check was not passed.

__init__(value, *tags, **options)

Creates the new Condition.

Parameters:
  • value – value to be checked (object, function, regex, string, boolean, list).
  • tags – list of tags for this Condition to be active.
  • options
    • ignore_case (bool.): False by default, ignore case of string conditions or not.
    • search (bool.): False by default, perform the search or match regexes and strings when checking.
tags = None

Set of tags to be considered active (read-only)

setup()

Sets the additional Access.spec info: Condition.NUMBER, Condition.STRING, Condition.LIST, Condition.REGEX, Condition.DICT, Condition.BOOLEAN.

Sets Condition.check() to the appropriate checking function depending on the value type.

check(message, context)

Checks the possibility of handling the message in the specified context. Returns the tuple of (rank, check_result) where rank shows the relevance of the condition. If less than 0 it means condition is not satisfied and completely irrelevant. Zero rank is mostly used for logical conditions (True/False) that cannot be measured numerically. Check result keeps the result of functional (user-defined, regular expression) check.

Note

the default implementation returns Condition.NO_CHECK and should be overwritten in Condition.setup() method.

Parameters:
  • message (List.) – message to check.
  • context (Dict.) – checking context.
Returns:

Tuple of (rank, check_result) or just rank value.

list

Returns the list of inner conditions.

class gt.core.TrueCondition

Bases: gt.core.Condition

Condition that is always satisfied.

class gt.core.Event(value)

Bases: gt.core.Access

Event contains the user object (value or function) to be called if the Condition was satisfied. It provides Event.pre and Event.post properties to assign functions to be executed before and after the user object call.

RESULT = 'result'

Object call result context parameter.

__init__(value)

Wraps in Access the value to be called.

pre_event = None

Pre-event, Event class instance.

post_event = None

Post-event, Event class instance.

run(message, context)

Does the Access call to the event object with the message and context. If Event.pre event is specified it will be called first. If its result is non-negative the object will not be called at all. If Event.post event is specified it will be called after the object and the context will contain the object call result in Event.RESULT context parameter. If its result is non-negative, it will be returned instead of object call result.

Parameters:
  • message (list.) – message to send to the event.
  • context (dict.) – running context.
Returns:

tuple of (call result, Access.value).

Return type:

tuple.

pre

Sets/gets the pre-event object. Use pre_event attribute to assign an Event instance directly.

post

Sets/gets the post-event object. Use post_event attribute to assign an Event instance directly.

class gt.core.Handler

Bases: gt.core.Abstract

Handler is used for routing of messages to handling functions called events (Event) basing on the specified condition (Condition). Each condition has a corresponding event. When handling a message, Handler class searches for the condition that has the highest rank and calls Handler.unknown_event if nothing found.

The condition could be limited to be active only if its set of tags (Condition.tags) is a subset of the Handler set of tags. List of active conditions and events is in Handler.active_events property.

ANSWER = 'answer'

Answer context parameter, if equal to Handler.RANK the condition rank will be included in the answer.

SENDER = 'sender'

Sender context parameter. When the event is called, contains the reference to the top-level handler.

CONDITION = 'condition'

Condition context parameter. When the event is called, contains the check result.

EVENT = 'event'

Event context parameter. When the pre/post/event is called, contains the reference to the event function.

RANK = 'rank'

Rank context parameter. When the event is called, contains the check rank.

NO_HANDLE = (False, -1, None)

Returned by Handler.handle() if no handler found.

active_events = None

Tuple of events which are eligible for the current tags (read-only).

unknown_event = None

Event to be executed when no handler found for the message.

on_access(condition_access, event_access)

Adds the Condition and Event instances pair.

Parameters:
  • condition_access (Condition.) – condition to be checked.
  • event_access (Event.) – event to be executed if the condition is satisfied.
on(condition, event, *tags)

Adds the condition - event pair.

Parameters:
  • condition – condition for the event (function, abstract, value).
  • event – function, abstract, or value to be called if condition is satisfied.
  • tags – list of tags to bind the condition to the handler’s state.
on_any(event)

Adds the event that will be triggered on any message.

Parameters:event – function, abstract or value to be called.
off(condition, event)

Removes the condition - event pair.

Parameters:
  • condition – condition to be removed (no matter Condition type or not)
  • event – event to be removed (no matter Event type or not).
off_any(event)

Removes the event that will be triggered on any message.

Parameters:event – event to be removed.
off_condition(condition)

Removes all events for the condition.

Parameters:condition – condition to be removed.
off_event(event)

Removes all occurrences of the event.

Parameters:event – event to be removed.
get_events(condition=None)

Gets the events for the specified condition. If the condition is not specified returns the list of events that trigger on any message.

Parameters:condition – condition to get the events.
Returns:list of events found.
Return type:list.
clear_events()

Removes all conditions and events.

update_tags()

Called by Handler.update_events() to get the set of tags describing the current state.

Returns:set of tags describing the current state.
Return type:set.
update_events()

Called by Handler.update() when the list of active events needs to be updated (for example, after the new event was added or tags were changed).

update()

Update is called manually or by handler itself when something is changed. If the tag set returned by Handler.update_tags() is different from Handler.tags, Handler.update_events() will be called to re-populate the list of active events.

handle(message, context)

Checks the list of condition-event pairs to find the condition with the highest rank for the message and context and then executes the corresponding event.

Parameters:
  • message (list.) – list of message parts.
  • context (dict.) – message handling context.
Returns:

Tuple of (event_result, condition_rank, event_found). If no condition was found, rank is equal to -1 (Handler.NO_HANDLE will be returned if not overridden by Handler.unknown_event).

Return type:

tuple.

__call__(*message, **context)

Answers on the incoming message. Calls Handler.handle() method and returns the first element from its reply. If the context parameter Handler.ANSWER is equal to Handler.RANK - returns the rank is well.

Parameters:
  • message – message items.
  • context – message context.
Returns:

handling result or tuple of (handling_result, condition_rank).

tags

Sets/gets the set of the current tags. Does not call Handler.update().

events

Gets the list of all conditions and events regardless of the current tags.

Graph Classes

class gt.core.Element(owner=None)

Bases: gt.core.Handler

Element is a part of a complex system (e.g. graph). It has an owner and could be passed in forward and backward directions by some process.

SET_PREFIX = 'set'

Default prefix for property change notifications.

SEP = '_'

Notifications separator

OWNER = 'owner'

Owner context parameter

NAME = 'name'

Name context parameter for notifications.

OLD_VALUE = 'old-value'

Old value context parameter for notifications (e.g. keeps the old owner when changing it).

NEW_VALUE = 'new-value'

New value context parameter for notifications.

__init__(owner=None)

Creates the Element, attaching it to the owner, if specified.

Parameters:owner (Graph.) – graph to own this element.
is_forward(message)

Checks the message about passing the element in a forward direction.

Parameters:message (list.) – message to be checked
Returns:forward or not.
Return type:bool.
can_go_forward(*message, **context)

Passing forward condition.

on_forward(event)

Adds the event to be called when this element is passed in a forward direction.

Parameters:event – user function to be called, will be wrapped in Event.
off_forward()

Removes the forward condition and event.

is_backward(message)

Checks is the message about passing the element in a backward direction.

Parameters:message (list.) – message to be checked
Returns:backward or not.
Return type:bool.
can_go_backward(*message, **context)

Passing backward condition.

on_backward(event)

Adds the event to be called when this element is passed in a backward direction.

Parameters:event – user function to be called.
off_backward()

Removes the backward condition and event.

on_visit(event)

Adds the event to be called when this element is visited .

Parameters:event – user function to be called.
off_visit()

Removes the visit condition and event.

static add_prefix(msg, prefix)

Adds the prefix to the message, used when generating a notification about property change (e.g. owner). If the prefix is already in place does nothing.

Parameters:
  • msg (str.) – message with the property name.
  • prefix (str.) – prefix to add.
change_property(name, value)

Sets the property to the new value with the notification, if needed. For example, when setting the owner, old and new owners will be notified about the change with the message generated with Element.add_prefix() method.

Parameters:
  • name (str.) – property name.
  • value – property value.
owner

The graph this element belongs to.

class gt.core.Notion(name, owner=None)

Bases: gt.core.Element

Notion is an element with name. Represent the graph vertex.

__init__(name, owner=None)

Creates the new Notion with the specified name.

Parameters:
  • name (str.) – notion name.
  • owner (Graph.) – notion’s owner.
name

Sets/gets the notion name using Element.change_property() method.

class gt.core.ActionNotion(name, action, owner=None)

Bases: gt.core.Notion

Action notion is a notion that executes the user function when passed forward.

__init__(name, action, owner=None)

Creates the new ActionNotion with the specified name and action.

Parameters:
  • name – notion name.
  • action – action, any object to be wrapped in Event.
  • owner (Graph.) – notion’s owner.
action

Sets/gets the user function to be triggered using Element.on_forward() method.

class gt.core.ComplexNotion(name, owner=None)

Bases: gt.core.Notion

Complex notion is a notion that contains other notions via relations. To add a relation just set its subject to the corresponding ComplexNotion.

do_relation(*message, **context)

Subject change event, updates references if a sub-notion was connected/disconnected.

Returns:True if subject’s change was successful.
Return type:bool.
do_forward(*message, **context)

Forward message event.

Returns:the list of relations or just single relation if the relations list length == 1
do_visit()

Visit event.

Returns:the list of relations to visit.
Return type:tuple.
remove_all()

Disconnects all relations.

relations

Gets the list of relations (read-only).

class gt.core.Relation(subj, obj, owner=None)

Bases: gt.core.Element

Relation is a connection between two notions, directed from the subject to object. Represents the graph arc.

SUBJECT = 'subject'

Subject context parameter, used in change subject notifications.

OBJECT = 'object'

Object context parameter, used in change object notifications.

__init__(subj, obj, owner=None)

Creates the new Relation between subj and obj.

Parameters:
  • subj (ComplexNotion.) – source notion.
  • obj (Notion.) – target notion.
  • owner (Graph.) – relation’s owner.
subject

Sets/gets the subject using Element.change_property() method.

object

Sets/gets the object using Element.change_property() method.

class gt.core.NextRelation(subj, obj, condition=None, owner=None, **options)

Bases: gt.core.Relation

Next relation returns its Relation.object to the forward message if the specified condition was satisfied. If the condition is not set, TrueCondition is used.

__init__(subj, obj, condition=None, owner=None, **options)

Creates the new NextRelation with the specified condition.

Parameters:
  • subj (ComplexNotion.) – subject.
  • obj (Notion.) – object.
  • condition – condition value, will be wrapped in Condition.
  • owner (Graph.) – owner.
  • options – Condition options, like in Condition.__init__(). When setting the new condition, options will be reapplied.
condition_access = None

Passing condition, a Condition class instance. Default value is TrueCondition.

can_pass(*message, **context)

Forward message condition, will call NextRelation.check_condition() if the message is a forward one.

check_condition(message, context)

Returns the result of condition’s Condition.check() call.

do_next(*message, **context)

Next event.

Returns:Relation.object.
Return type:Notion.
do_visit(**context)

Visit event.

Returns:Relation.object.
Return type:Notion.
set_condition(value)

Sets the new condition, wrapping the value in the Condition.

Parameters:value – new condition value.
condition

Sets/gets the value of the current condition. Note that it does NOT return a Condition instance. Use NextRelation.condition_access for direct access instead.

class gt.core.ActionRelation(subj, obj, action, owner=None)

Bases: gt.core.Relation

Action relation executes the user function when passed forward.

__init__(subj, obj, action, owner=None)

Creates the new ActionRelation.

Parameters:
  • subj (ComplexNotion.) – subject.
  • obj (Notion.) – object.
  • action – action value, will be wrapped in Access.
  • owner (Graph.) – owner.
action_access = None

Passing action, a Access class instance.

do_act(*message, **context)

Executes the action.

Returns:If ActionRelation.action call result is not None and the object is not None too returns tuple (action_result, Relation.object). Otherwise returns action result OR Relation.object.
action

Sets/gets the action value, wrapping it in Access. When called for reading, returns the Access.value. Use ActionRelation.action_access to access Access class instance.

class gt.core.ParsingRelation(subj, obj, condition=None, owner=None, **options)

Bases: gt.core.NextRelation

Parsing relation: should be passable in a forward direction (otherwise returns ParsingProcess.ERROR). If passed, consumes the amount of text equal to the rank using ParsingProcess.PROCEED command.

__init__(subj, obj, condition=None, owner=None, **options)

New options in addition to NextRelation.__init__():

  • optional (bool.): do not return ParsingProcess.ERROR if the condition was not satisfied, False by default.
  • check_only (bool.): do not return ParsingProcess.PROCEED if the condition was satisfied, False by default.
optional = None

Do not return error if cannot be passed

check_only = None

Do not consume text when passed.

check_condition(message, context)

Checks the NextRelation.condition against the value of ParsingProcess.TEXT context parameter.

do_next(*message, **context)

Consume the parsed part of the text equal to rank.

Returns:Tuple ({ParsingProcess.PROCEED: condition_rank}, Relation.object) if ParsingRelation.check_only is False, just Relation.object otherwise.
on_error(*message)

Unknown_message event.

Returns:ParsingProcess.ERROR
Return type:str.
class gt.core.SelectiveNotion(name, owner=None)

Bases: gt.core.ComplexNotion

Selective notion is a ComplexNotion that consists of only one sub-notion. It resembles “switch” statement from programming languages like Java or C++. SelectiveNotion tries all its relations and uses the one with the highest rank and processed without errors. After each try, the context state will be restored to make sure all relations use the same context data. Like in the original switch statement it is possible to specify the SelectiveNotion.default relation to be used if nothing worked.

CASES = 'cases'

Cases state parameter, keeps the list of remaining cases for re-tries.

get_best_cases(message, context)

Searches for the relation with the highest rank for the specified message and context.

Parameters:
  • message (list.) – message items.
  • context (dict.) – message handling context.
Returns:

the relation(s) with the highest rank or SelectiveNotion.default relation, if specified.

Return type:

list.

do_relation(*message, **context)

Subject change event: additional check for the default relation to have this notion as a subject.

can_go_forward(*message, **context)

Forward condition: makes sure this is a first visit of this element (no state is stored in the context). Re-try event will be used otherwise.

do_forward(*message, **context)

Forward event: if this notion has only one relation, it just returns it without any checks; otherwise calls SelectiveNotion.get_best_cases() to get the best relation(s) and returns the first one from the list.

Other relations with the same rank will be saved to the state SelectiveNotion.CASES parameter for retries. Note that element saves the context state to the process stack using StackingProcess.PUSH_CONTEXT command if there is more than one case to try.

can_retry(*message, **context)

Retry condition: if the previous case did not work (ParsingProcess.ERROR in the message), let’s try something else.

do_retry(**context)

Retry event: if there are other cases to try - let’s do this, if not - clear the state and keep the error propagating to the top.

can_finish(*message, **context)

Finish condition: there is a saved state and no error happened.

do_finish()

Finish event: forget the saved context using StackingProcess.FORGET_CONTEXT command and clear the state using StatefulProcess.CLEAR_STATE command.

default

Sets/gets the default relation. Only the relation with the subject equal to this element can be used as the default.

class gt.core.LoopRelation(subj, obj, condition=None, owner=None)

Bases: gt.core.NextRelation

Loop relation specifies the number of times the Relation.object notion should appear. Similar to “for” loops in programming languages. The number of times is specified as a condition, possible conditions are: numeric (n; m..n; m..; ..n), wildcards (“*”, ”?”, “+”), True (infinite loop), and a user function.

ITERATION = 'i'

Current iteration context parameter.

check_condition(message, context)

Forward condition. In this class this condition works only for infinite loops.

set_condition(value)

Sets the new condition. In addition to NextRelation.set_condition() updates the events using Handler.update_events() to keep only events which work for the specified loop condition type.

Parameters:value – new condition value.
is_wildcard()

Is a wildcard loop.

is_numeric()

Is a numeric loop.

is_infinite()

Is an infinite loop.

is_custom()

Is a custom loop: non-empty callable condition.

is_flexible()

Is a flexible loop: the condition has no finite limit of repetitions, either lower or higher.

is_general()

Is a general type: numeric, wildcard or infinite, but not a custom.

is_looping(context)

Checks if this loop is active now by presence of LoopRelation.ITERATION key in the element’s state.

Parameters:context (dict.) – message handling context
get_bounds()

Gets the limits of the loop.

Returns:Tuple of (lower_bound, upper_bound). For loops with no lower bound (like ..n) it equals to 0, for loops with no upper bound it equals to infinity.
Return type:tuple.
get_next_iteration_reply(i=1)

Gets the next iteration reply: sets the state to the iteration number using StatefulProcess.SET_STATE command and saves the context if the loop is flexible using StackingProcess.PUSH_CONTEXT command. If the iteration number is higher than 1, discards the previous context state using StackingProcess.FORGET_CONTEXT command.

Parameters:i (int.) – iteration number.
Returns:list of commands: StatefulProcess.SET_STATE with LoopRelation.ITERATION equal to i, discarding and saving context commands if the loop LoopRelation.is_flexible().
Return type:list.
can_start_general(*message, **context)

Forward condition for starting of general loops: checks for the first visit; loop event will be used otherwise.

do_start_general()

Forward event for starting of general loops; returns the first iteration using LoopRelation.get_next_iteration_reply().

can_loop_general(*message, **context)

Loop condition for the general loops: makes sure there are no errors and iteration is more than 1.

do_loop_general(**context)

Loop event for general loops: if the iteration number is within LoopRelation.get_bounds(), increases it and repeats the loop. Stops the loop otherwise, clearing the state using StatefulProcess.CLEAR_STATE command and discards the saved context using StackingProcess.FORGET_CONTEXT, keeping it in the actual state.

can_error_general(*message, **context)

Error condition for the general loops (ParsingProcess.ERROR in the message).

do_error_general(**context)

Error event for the general loops: if the loop condition is satisfied just clears the state using StatefulProcess.CLEAR_STATE command restores the context to the last good state using StackingProcess.POP_CONTEXT command and clears the error using Process.NEXT. If the number of repetitions is less than needed - discards the saved context using StackingProcess.FORGET_CONTEXT command clears the state and keeps the error.

can_loop_custom(*message)

Forward event for custom loops.

do_loop_custom(*message, **context)

Loop event for custom loops. Calls the user function from NextRelation.condition, sending the value of the current iteration in the context parameter LoopRelation.ITERATION. The call result will be the new number of the iteration. If it is equal to 0, False, or None - stops the loop by clearing the state using StatefulProcess.CLEAR_STATE command.

do_error_custom()

Error event for the custom loops: just clears the state using StatefulProcess.CLEAR_STATE command.

can_break(*message, **context)

Break condition: checks for the message to be ParsingProcess.BREAK and the loop to be in progress using LoopRelation.is_looping().

do_break()

Break event: changes the process direction to forward using Process.NEXT command, clears the loop state using StatefulProcess.CLEAR_STATE and the context state using StackingProcess.FORGET_CONTEXT if the loop LoopRelation.is_flexible().

can_continue(*message, **context)

Continue condition: checks for the message to be ParsingProcess.CONTINUE and the loop to be in progress using LoopRelation.is_looping().

do_continue(*message, **context)

Continue event: changes the process direction to forward using Process.NEXT, starts the new iteration using LoopRelation.do_loop_general() or LoopRelation.do_loop_custom() depending on the loop type.

class gt.core.Graph(root=None, owner=None)

Bases: gt.core.Element

Graph is a container for elements like Notions, Relations, and other Graphs. It allows easy search and processing of the elements.

__init__(root=None, owner=None)

Creates the new Graph with the specified root notion and owner. The name of the graph is equal to the name of its root notion.

Parameters:
  • root – if of String type, Graph will create the new ComplexNotion element with the corresponding name and owner to be used as a root. The root notion will be saved into the Graph.root property of the graph.
  • owner (Graph.) – owner of this graph.
get_notion_search_rank(notion, criteria)

Gets the rank of the notion when searching by criteria. Used as a comparator for notions search.

Parameters:
  • notion (Notion.) – the notion to calculate the rank.
  • criteria – searching criteria: regex, string or user function.
Returns:

similarity rank: match length for regex, length of the string if the string is equal to the notion’s name, the result of user function call.

Return type:

int.

search_elements(collection, comparator, criteria)

Searches for the elements within the collection to find the ones with the highest rank according to the specified criteria.

Parameters:
  • collection (list.) – list of the elements of the same type (Notion or Relation).
  • comparator – comparison function.
  • criteria – search criteria.
Returns:

elements with the highest rank.

Return type:

list.

notions(criteria=None)

Finds the notions by the specified criteria. If more than 1 notion has the highest rank, the list will be returned. Calls Graph.search_elements() with Graph.get_notion_search_rank() as a comparator function.

Parameters:criteria – user function, regex, or string to compare with the notion name. If not specified, all notions will be returned.
Returns:notions found.
Return type:tuple.
notion(criteria)

Finds a single notion by the criteria. Calls Graph.notions() to get the list of notions than returns a first one.

Parameters:criteria – search criteria.
Returns:notion found.
Return type:Notion.
get_relation_search_rank(relation, criteria)

Gets the rank of the relation when searching by criteria. Used as a comparator for relations search.

Parameters:
  • relation (Relation.) – the relation to calculate the rank.
  • criteria – searching criteria: a dictionary or user function. The dictionary contains Relation.SUBJECT or Relation.OBJECT keys to specify the notion which should be a subject or object for the relation.
Returns:

similarity rank: the result of the user function call or -1 (no subject/object equals to criteria), 0 (subject or object is equal to criteria), 1 (both subject and object are equal).

Return type:

int.

relations(criteria=None)

Finds the relations by the specified criteria. If more than 1 relation has the highest rank, the list will be returned. Calls Graph.search_elements() with Graph.get_relation_search_rank() as a comparator function.

Parameters:criteria – user function or dictionary with target Relation.SUBJECT or Relation.OBJECT values. If not specified, all relations will be returned.
Returns:relations found.
Return type:tuple.
relation(criteria=None)

Finds a single relation by the criteria. Calls Graph.relations to get the list of relations than returns a first one.

Parameters:criteria – search criteria.
Returns:relation found.
Return type:Relation.
do_element(**context)

Owner change event. This event appears when the element changes the owner. When received, the graph will add or remove the element from the corresponding list of notions or relations. If the root notion changes owner, the graph will set the Graph.root to None.

do_forward()

Forward event. Returns Graph.root value.

Returns:root notion.
Return type:Notion.
do_visit()

Visit event. Returns Graph.root value.

Returns:root notion.
Return type:Notion.
root

Setter/getter of the root notion. The new root should belong to the graph.

name

Setter/getter of the graph name. The name of the graph is equal to the name of the Graph.root notion.

class gt.core.GraphBuilder(graph=None)

Bases: object

Graph builder helps to create Graph. It uses chained operations to assemble the graph, connecting elements to each other, for example:

builder.complex('complex').next_rel().notion('simple')

The current element to attach the new one is stored in GraphBuilder.current property.

__init__(graph=None)

Create the new GraphBuilder using specified graph.

Parameters:graph – is of string type will be used to create the new graph.
graph = None

Current graph

current = None

Current graph element to attach the new ones.

attach(new)

Attaches the new element to the GraphBuilder.current depending on its type. If the new element is a Notion and the current element is a Relation, the new element becomes a Relation.object of the relation. If the new element is a relation, and the current element is a ComplexNotion, the current element becomes a Relation.subject of the new relation. Set the current element to None to avoid this behavior.

Parameters:new (Element.) – the new element to attach and set as a current.
Returns:self.
Return type:GraphBuilder.
complex(name)

Attaches new ComplexNotion with the specified name.

Parameters:name (str.) – new complex notion name.
Returns:self.
Return type:GraphBuilder.
notion(name)

Attaches new Notion with the specified name.

Parameters:name (str.) – the new notion name.
Returns:self.
Return type:GraphBuilder.
act(name, action)

Attaches new ActionNotion with the specified name and action.

Parameters:
Returns:

self.

Return type:

GraphBuilder.

next_rel(condition=None, obj=None, **options)

Attaches new NextRelation with the specified condition and object.

Parameters:
  • condition – the passing condition.
  • obj (Notion.) – the object of the new relation.
  • options – options to be passed to NextRelation.__init__().
Returns:

self.

Return type:

GraphBuilder.

act_rel(action, obj=None)

Attaches new ActionRelation with the specified action and object.

Parameters:
  • action – the action value (user function, etc.).
  • obj (Notion.) – the object of the new relation.
Returns:

self.

Return type:

GraphBuilder.

parse_rel(condition, obj=None, **options)

Attaches new ParsingRelation with the specified condition and object.

Parameters:
  • condition – the passing condition.
  • obj (Notion.) – the object of the new relation.
  • options – options to be passed to ParsingRelation.__init__().
Returns:

self.

Return type:

GraphBuilder.

select(name)

Attaches new SelectiveNotion with the specified name.

Parameters:name (str.) – new selective notion name.
Returns:self.
Return type:GraphBuilder.
default()

If the GraphBuilder.current element is a Relation and its subject is a SelectiveNotion instance, this relation will be set as a SelectiveNotion.default.

Returns:self.
Return type:GraphBuilder.
loop_rel(condition, obj=None)

Attaches new LoopRelation with the specified condition and object.

Parameters:
  • condition – the iteration condition.
  • obj (Notion.) – the object of the new relation.
Returns:

self.

Return type:

GraphBuilder.

sub_graph(name)

Creates the new sub-graph with the specified name. If the current GraphBuilder.graph is None, the new graph will be used as a current. Otherwise the GraphBuilder.current element will be set to the Graph.root of the new graph.

Returns:self.
Return type:GraphBuilder.
pop()

Goes to the Graph.root element of the Element.owner of the GraphBuilder.current element’s graph.

Returns:self.
Return type:GraphBuilder.
set_current(element)

Sets the element as a GraphBuilder.current, using its owner as a current GraphBuilder.graph.

Parameters:element (Element.) – new current element.
Returns:self.
Return type:GraphBuilder.
back()

If the GraphBuilder.current is a Notion, searches for any Relation that has it as a Relation.object and sets it as a current. If the current element is a Relation, sets its Relation.subject notion as a current.

Returns:self.
Return type:GraphBuilder.
__getitem__(element)

GraphBuilder.current element helper.

Parameters:element – if of String type, sets the GraphBuilder.current element to the notion with this name, otherwise sets the specified element as a current.
Returns:self.
Return type:GraphBuilder.

Process Classes

class gt.core.Process

Bases: gt.core.Handler

Process goes from an Element to element, asking what to do next with a Process.query. The answer from the Process.current element will be processing using Handler methods. If the answer is a list, its items will be put to the queue and processed one by one. If the answer is another element, it will be the next current element to ask for directions.

The processes are usually started with the start element and some context to be used in the dialog with the elements:

p = Process()
print(p(start_element, destination="Orion"))
NEW = 'new'

New command. Clears the process internals when the process should be started from the scratch.

OK = 'ok'

Ok command. Stops the process with an “ok” result.

STOP = 'stop'

Stop command. Stops the process with a “stop” result.

QUERY = 'query'

Query command (needs dict). Sets Process.query to the specified value.

NEXT = 'next'

Next element command.

PREVIOUS = 'previous'

Previous element command.

CURRENT = 'current'

Non-empty current element tag; queue item field with the current element.

MESSAGE = 'message'

Non-empty message tag; queue item field with the current message.

EMPTY_MESSAGE = 'empty_message'

Empty message tag, shows that the current message is empty.

FORWARD = set(['next'])

Set of forward queries to identify the direction.

BACKWARD = set(['break', 'continue', 'error', 'previous'])

Set of backward queries to identify the direction.

context = None

Process context.

query = None

Current query. An initial value is Process.NEXT.

message = None

Current message (read-only).

current = None

Current element (read-only).

skip()

Removes the first item of the current Process.message. Useful when it is unknown and cannot be processed.

can_push_queue()

Queue push condition: if the first item of the Process.message is an Abstract or function, the process has to ask it about directions and handle the reply. To do this, a new queue item is created.

do_queue_push()

Queue push event: adds the new queue item with Process.CURRENT equals to the first Process.message item and Process.MESSAGE equals to Process.QUERY so the new current element will be asked with the current Process.query.

can_pop_queue()

Queue pop condition: when the current queue item is empty, we can remove it.

do_queue_pop()

Queue pop event: removes the first element from the queue.

do_query()

Query event: sends the message the with the Process.query value to Process.current element .

Returns:the answer of the element or True.
can_clear_message(*message)

Cleanup condition: can we remove an empty message item.

do_clear_message()

Cleanup event.

do_finish()

Finish event: returns the first message item with the finish value.

Returns:Process.STOP or Process.OK or a boolean value.
update_tags()

Checks the current values of the Process.message, queue, Process.current and returns the set of tags for the current state. Override to add new tags, see Handler for the details.

setup_events()
Sets up the process events and state tags. Tags are:
on_new(message, context)

New ‘special’ event: called when starting the handle loop and Process.NEW command is specified. This event has no conditions and is called by Process.handle() directly.

on_resume(message, context)

Resume ‘special’ event: called when resuming the stopped process. This event has no conditions and is called by Process.handle() directly.

handle(message, context)

In contrast with Handler.handle(), process handle does not stop when the message is handled, but continues handling with the result of the previous call.

class gt.core.SharedProcess

Bases: gt.core.Process

Shared process supports context modification commands to share data between elements using context parameters .:

p = SharedProcess()
p({SharedProcess.ADD_CONTEXT: {'key': 'skeleton'}})
ADD_CONTEXT = 'add_context'

Add context command (requires dict). Adds the specified parameter and value to the context, skips existing ones.

UPDATE_CONTEXT = 'update_context'

Update context command (requires dict). Updates the specified key(s) in the context.

DELETE_CONTEXT = 'delete_context'

Delete context command (requires key or key list). Deletes the specified keys(s) from the context.

can_add_context(*message)

Add context condition: checks if there is a SharedProcess.ADD_CONTEXT command with data in the dictionary.

do_add_context()

Add context event; adds parameters to the context, skipping existing ones.

can_update_context(*message)

Update context condition: checks if there is a SharedProcess.UPDATE_CONTEXT command with data in the dictionary.

do_update_context()

Update context event: adds or replaces context parameters.

can_delete_context(*message)

Delete context condition: checks if there is a SharedProcess.DELETE_CONTEXT command.

do_delete_context()

Delete context event; deletes the single key or all the keys from the list.

setup_events()

Sets up the events and state tags. All commands require Condition.DICT.

class gt.core.StackingProcess

Bases: gt.core.SharedProcess

Process that can save and restore the context. Useful for cases when the process needs to try various paths in a graph and then rollback to the state it had at the crossroads.

To perform the rollback, the process records all change actions done via SharedProcess commands and plays them back in “undo” command style. If no rollback is needed, the saved context can be discarded.

PUSH_CONTEXT = 'push_context'

Push the current context to the undo stack.

POP_CONTEXT = 'pop_context'

Restore the context from the top of the undo stack.

FORGET_CONTEXT = 'forget_context'

Discard the saved context at the top of the undo stack, keeping the changed context as is.

TRACKING = 'tracking'

Non-empty undo stack tag.

do_push_context()

Push context event: start recording changes.

do_pop_context()

Pop context event: un-does changes from the top of the undo stack and removes the saved context.

do_forget_context()

Forget context event: discard the top context from the undo stack.

setup_events()

Sets up the events and state tags. All commands require Condition.STRING, pop and forget commands also require non-empty undo stack (StackingProcess.TRACKING).

on_new(message, context)

Clears the undo stack if a new process started.

class gt.core.StatefulProcess

Bases: gt.core.StackingProcess

Allows saving of private element data to the context. Only works for the Process.current:

ActionNotion('Changed my mind', {StatefulProcess.SET_STATE: {'mind': 'New York'}})

Note

Element state is a part of rollback process, but only at the top level, for example if the state is a dict its internals will not be restored.

STATE = 'state'

The name of the context parameter to access the state.

SET_STATE = 'set_state'

Set the state command (requires dict), applicable for the current process element.

CLEAR_STATE = 'clear_state'

Clear the state command, remove saved state from the context.

HAS_STATES = 'has_states'

‘Has previously saved states’ tag.

do_query()

Query event: adds the current element’s state as the StatefulProcess.STATE context parameter. At the end of this method the state is removed from the context to keep it private.

can_set_state(*message)

Set state condition: checks for StatefulProcess.SET_STATE command in the message.

do_set_state()

Set state event: saves the value of the command to the internal dictionary of states.

do_clear_state()

Clear state condition: checks for StatefulProcess.CLEAR_STATE.

setup_events()

Sets up the events and state tags. Set command requires Condition.DICT and Process.CURRENT, clear command requires Process.CURRENT, Condition.STRING and previously saved states (StatefulProcess.HAS_STATES tag).

on_new(message, context)

New event: clears the states if a new process started.

class gt.core.ParsingProcess

Bases: gt.core.StatefulProcess

Takes the text as an input; sends it to the graph elements as a context parameter. If an element responds with ParsingProcess.PROCEED, cuts off a piece of specified length from the beginning of the text.

Supports ParsingProcess.ERROR command to indicate a problem and possible stop of lookahead. Supports looping commands ParsingProcess.BREAK and ParsingProcess.CONTINUE; to change the direction back to forward uses Process.NEXT.

PROCEED = 'proceed'

Proceed command (requires a dict with numeric positive value); goes with the length of the parsed text piece.

ERROR = 'error'

Error command; stops the forward processing and changes the Process.query to this value.

BREAK = 'break'

Break command; stops the forward processing and changes the Process.query to this value.

CONTINUE = 'continue'

Continue command; stops the forward processing and changes the Process.query to this value.

PARSED_LENGTH = 'parsed_length'

Context parameter with the total length of the parsed text.

TEXT = 'text'

Context parameter with the current text.

LAST_PARSED = 'last_parsed'

Context parameter with the last parsed text piece.

is_parsed()

Checks whether the text was completely and successfully parsed.

Returns:True if the process has a forward direction and there is no more text to parse.
handle(message, context)

Calls the Process.handle().

Returns:If the text was not fully parsed (see ParsingProcess.is_parsed()), returns False; otherwise returns the result of the superclass handle call.
can_proceed(*message)

Proceed condition: checks for ParsingProcess.PROCEED and the positive distance.

do_proceed()

Proceed event: cuts off the beginning of the text, updates ParsingProcess.TEXT, ParsingProcess.PARSED_LENGTH and ParsingProcess.LAST_PARSED context parameters.

do_turn()

Turn event: sets Process.query to the value of ParsingProcess.BREAK, ParsingProcess.CONTINUE, ParsingProcess.ERROR, or Process.NEXT. Clears the current message.

setup_events()

Sets up the events and state tags. Direction-changing commands require Condition.STRING tag, ParsingProcess.PROCEED command requires Condition.DICT tag.

on_new(message, context)

New event: sets the direction to Process.NEXT, ParsingProcess.PARSED_LENGTH to 0 and ParsingProcess.LAST_PARSED to the empty string.

text

Gets the current text.

parsed_length

Gets the total parsed text length.

last_parsed

Gets the last parsed text piece.

class gt.core.VisitorProcess

Bases: gt.core.Process

Visitor process implements ‘visitor’ pattern to visit each graph element once. It is useful for exporting graphs into files.

VISIT = 'visit'

Visit command; asks the element about its connections with the other graph elements.

visit_event = None

Visit event.

visited = None

The visited path.

can_push_queue()

For this class only Abstract instances could be put to the queue.

do_query()

This class queries only not yet visited elements, others will be skipped using Process.skip() method. Visit possibility is evaluated using VisitorProcess.visit() method.

visit()

This method checks is the Process.current already visited and if no calls VisitorProcess.visit_event before allowing to visit it.

on_new(message, context)

Clean up the visited list.

Table Of Contents

Previous topic

Developer’s Guide

Next topic

Graph-talk Debug API

This Page