% $Id: objects.tex 347 2008-02-25 00:53:43Z Franz $
\chapter{Classes and Objects\label{pyclips-objects}}

As previously stated in the introduction, \pyclips{} provides classes and
objects to access CLIPS ``\emph{entities}''. It could be preferable to
refer to counterparts ``living'' in the CLIPS subsystem as \emph{entities}
than as \emph{objects}, because it is common practice in OOP to give
the name of ``\emph{objects}'' to class instances: since CLIPS has its
own object oriented structure (in fact there are \emph{classes} in
CLIPS, and therefore also \emph{instances} of these), calling these
structures simply \emph{objects} may generate confusion.

Entities in CLIPS are generated by \emph{constructs}, one for each type
of entity. In Python, the common way to create something is to instance
an \code{object} for a certain \keyword{class}. So it seemed straightforward
to make a class for each of these entities, and to substitute the constructs
used in CLIPS to create entities with \emph{factory functions}. These
functions are defined at module level, and have names of the type
\function{Build\emph{Entity}()} where \function{\emph{Entity}} is the
type of entity that has to be created. The only exception for this are
\class{Fact} objects, which are created in several ways from
\class{Template}s or \function{Assert}ions.

There is another way to create entities in the CLIPS subsystem, that is
directly using the \function{Build()} function with a full CLIPS
construct as string argument. However, this function does not return
anything to the caller, so the created entity has to be sought after
creation to obtain a reference.

The \function{Build\emph{Entity}()} functions and the \function{Assert()}
function return objects of proper types (whose detailed list is given
below) which shadow the corresponding entities in the CLIPS space.

\note{Many objects in \pyclips{} have common features\footnote{The
current \pyclips{} implementation still does not make use of inheritance,
although it's likely that a future release will do.}, such as a
\emph{factory function} as stated above, or methods returning their name
or their so-called \emph{pretty-print form}: in the following detailed
documentation only the first occurrence of a feature will be described
thoroughly.}



\section{Wrapper Classes\label{pyclips-cl-wrapper}}

There are some simple classes that deserve a special mention in the
\pyclips{} module, used to represent in Python namespace the basic types
in CLIPS. These \emph{wrappers} are used to differentiate values that
CLIPS returns from other values that live in the Python space.
However these classes are equivalent to their Python counterparts, and
there is no need to pass objects converted to these classes to the module
functions. Here is a list containing the class names and their
equivalents in Python:

\begin{tableiii}{l|l|l}{class}{Class}{Type}{Python Equivalent}
	\lineiii{Integer}{\var{ClipsIntegerType}}{\class{int}}
	\lineiii{Float}{\var{ClipsFloatType}}{\class{float}}
	\lineiii{String}{\var{ClipsStringType}}{\class{str}}
	\lineiii{Symbol}{\var{ClipsSymbolType}}{\class{str}}
	\lineiii{InstanceName}{\var{ClipsInstanceNameType}}{\class{str}}
	\lineiii{Multifield}{\var{ClipsMultifieldType}}{\class{list}}
\end{tableiii}

A special object named \var{Nil} is defined, and is equivalent to
\code{Symbol('nil')} in comparisons and slot assignments. It is provided
to make code more readable in such situations. It has to be noticed that
also \var{Nil} evaluates to \var{False} in boolean tests: this also
yields for the explicit \code{Symbol('nil')} and \code{Symbol('FALSE')}
definitions\footnote{In this \class{Symbol} is different from \class{str}
as only the empty string evaluates to false in Python. However, it seemed
closer to the assumption that symbols in CLIPS are not to be considered
as ``\emph{literals}'' (they are more similar to implicitly defined
variables) to implement such behaviour, that can be reverted with an
explicit conversion to \class{str}.}.


\section{Template\label{pyclips-cl-Template}}

\class{Template}s are used to build \class{Fact} objects, that is, they
provide a systematic way to construct \class{Fact}s sharing a common
pattern, and the only way to define \class{Fact}s that have named
\class{Slots} (the equivalent of record \emph{fields} or \emph{structure
members} in other programming languages).

\begin{classdesc*}{Template}

This represents a copy of a \code{deftemplate} construct in the CLIPS
subsystem, and not a true \code{deftemplate} entity. More than one
\class{Template} object in Python can refer to the same
\code{deftemplate} entity in the CLIPS subsystem.

\begin{methoddesc}{BuildFact}{}
Build a \class{Fact} object using this \class{Template} without
asserting it. The created \class{Fact} \var{Slots} can be modified and
the \class{Fact} asserted using its \function{Assert} method.
\end{methoddesc}

\begin{memberdesc}[property]{Deletable}
Read-only property to verify if this \class{Template} can be deleted
from the CLIPS subsystem.
\end{memberdesc}

\begin{methoddesc}{InitialFact}{}
Return initial \class{Fact} in list created using this \class{Template}.
\end{methoddesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Template} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Read-only property returning the name in CLIPS of this \class{Template}.
The name identifies this entity in the CLIPS subsystem, and has nothing
to do with the name given to the corresponding object in Python.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next\footnote{CLIPS stores its objects (or entities) in ordered
lists, so it makes sense to ``iterate'' over these lists. However this
implementation of \pyclips{} does not implement \emph{iterators} (as
known in Python) on these classes: a way to do this is currently under
examination.} \class{Template} in the list of all \class{Template}s.
\var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{NextFact}{fact}
Return next \class{Fact} in list created using this \class{Template},
using the supplied \var{fact} as offset.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Template}.
\emph{Pretty-print forms} are often the code necessary to build a
construct in CLIPS, formatted in a way that makes it quite readable.
The result of the \function{PPForm()} method can be used as the argument
for the \function{Build()} top level function to rebuild the construct
once the \class{Environment} has been cleared\footnote{Actually
\emph{pretty-print forms} use fixed size buffers to build the representing
string: when such a form is too complex, the default buffer size of 8192
bytes can be insufficient. In this case the \emph{PPBufferSize} property
of the \emph{Memory} object can be used to allow the creation of properly
sized buffers.}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove the entity corresponding to this \class{Template} from the CLIPS
subsystem. This does not remove the corresponding Python object that has
instead to be deleted via the \keyword{del} statement or garbage
collected.
\end{methoddesc}

\begin{memberdesc}[property]{Slots}
\class{Deftemplate} \code{slots} information. This is itself an
object, having many methods, and deserves a special explaination.
\begin{methoddesc}{AllowedValues}{name}
Return a list of allowed values for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{Cardinality}{name}
Return \emph{cardinality} for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{DefaultValue}{name}
Return \emph{cardinality} for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{Exists}{name}
Return \constant{True} if \code{slot} specified by \var{name} exists,
\constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{HasDefault}{name}
Return one of the following values: \constant{NO_DEFAULT} if the
default value is set to \code{?NONE}, \constant{STATIC_DEFAULT} when
the default value is static and \constant{DYNAMIC_DEFAULT} when it
is dynamically generated (eg. \code{gensym}).
\end{methoddesc}
\begin{methoddesc}{IsMultifileld}{name}
Return \constant{True} if \code{slot} specified by \var{name} is
a \code{Multifield} value, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{IsSinglefield}{name}
Return \constant{True} if \code{slot} specified by \var{name} is
a single field value, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{Names}{}
Return the list of \code{slot} names.
\end{methoddesc}
\begin{methoddesc}{Range}{name}
Return \emph{numerical range information} for \code{slot} specified by
\var{name}.
\end{methoddesc}
\begin{methoddesc}{Types}{name}
Return names of \emph{primitive types} for \code{slot} specified by
\var{name}.
\end{methoddesc}
\end{memberdesc}

\begin{memberdesc}[property]{Watch}
Read-only property to verify if this \class{Template} is being watched.
\end{memberdesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Template}s is
\function{BuildTemplate()}, which has been discussed above.

\end{classdesc*}



\section{Fact\label{pyclips-cl-Fact}}

\class{Fact}s are one of the main entities in CLIPS, since it is
whether a \class{Fact} exists or not of that drives the subsystem in
the decision to fire or not certain \class{Rule}s. \class{Fact}s, as
seen above, can be created in several ways, that is either by directly
asserting sentences in string form, or by building them first from
\class{Template}s and then asserting them.


\begin{classdesc*}{Fact}

This represents a copy of a fact definition in the CLIPS subsystem, and
not a true fact entity. More than one Fact objects in Python can refer to
the same fact entity in the CLIPS subsystem. Many CLIPS functions return
a \class{Fact} object, but most \class{Fact} objects obtained from CLIPS
are \emph{read-only}\footnote{Actually, the main rule is that if a
\class{Fact} has been \function{Assert}ed then it is read-only. Note that
all \emph{shadow representations} of CLIPS asserted \code{fact} entities
are read-only.}. Read-only \class{Fact}s cannot be reasserted or modified
in \var{Slots}, and are provided for ``informational'' purposes only.

The argument can be a string with the same format of the
\function{Assert()} function seen in the previous chapter: in this case
the fact is created and asserted. Otherwise the argument can be a
\class{Template} object, and in this case the resulting \class{Fact} can
be modified and then asserted via the \function{Assert()} member
function.

\begin{methoddesc}{Assert}{}
Assert this \class{Fact}. Only \class{Fact}s that have been constructed
from \class{Template}s can be \function{Assert}ed using this method:
read-only \class{Fact}s can only be inspected with the other
methods/properties.
\end{methoddesc}

\begin{methoddesc}{AssignSlotDefaults}{}
Assign default values to \var{Slots} of this \class{Fact}.
\end{methoddesc}

\begin{methoddesc}{CleanPPForm}{}
Return only the second part of this \class{Fact}s \emph{pretty-print form}
-- which can be used to build the \class{Fact} itself as described above.
\end{methoddesc}

\begin{memberdesc}{Exists}{}
Is \constant{True} if this \class{Fact} has been asserted (and never
retracted), \constant{False} otherwise.
\end{memberdesc}

\begin{memberdesc}[property]{ImpliedSlots}
The list of all \emph{implied} \var{Slots} for this \class{Fact}.
\end{memberdesc}

\begin{memberdesc}[property]{Index}
Read-only property returning the index in CLIPS of this \class{Fact}. As
for other entities the \var{Name} is a unique identifier, as is the
\var{Index} for \class{Fact}s.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Fact} in the list of all \class{Fact}s. This list is
not based on \class{Module}s, but global to the CLIPS subsystem.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Fact}. In this case,
only the second part of the returned string (the one between parentheses)
can be used to build the \class{Fact} via the \function{Assert()}
function\footnote{This is also not always true: as said before, there is
no way to \function{Assert} \class{Fact}s that have named slots using a
string if there is not a \code{deftemplate} for this kind of
\class{Fact}. However, once a \class{Template} with the specified slots
has been created, this becomes possible.}.
\end{methoddesc}

\begin{methoddesc}{PPrint}{\optional{ignoredefaults}}
Print the \class{Fact} to the standard output. When \var{ignoredefaults}
is set to \constant{True} (the default), slots containing the default
values are omitted.
\end{methoddesc}

\begin{memberdesc}[property]{Relation}
Return only the name of the \emph{relation} that identifies this
\class{Fact}\footnote{The authors of CLIPS call a \emph{relation} the first
field of the \class{Fact} itself, although it is not needed to actually
represent a real relationship.} as a \class{Symbol}.
\end{memberdesc}

\begin{methoddesc}{Retract}{}
Retract this \class{Fact}: in other words, remove the corresponding
entity from the CLIPS subsystem. As in \function{Remove()} seen above,
this does not delete the corresponding Python object. \var{None} is
returned at the end of the list.
\end{methoddesc}

\begin{memberdesc}[property]{Slots}
Dictionary of \class{Fact} \var{Slots}. This member \emph{behaves} like
a \class{dict}, but is not related to such objects. In fact, the values
of \code{slots} are accessible using a \class{dict}-like syntax (square
brackets), but not all the members of \class{dict} are implemented.
\end{memberdesc}

Please note that \class{Fact}s have slightly different methods than
classes representing other entities in CLIPS: an instance of \class{Fact}
is created using the module-level \function{Assert()} function, and
removed using the \function{Retract()} member function: this syntax,
closer to the original CLIPS form, was seen as the preferred method instead
of using a name such as \function{BuildFact()} for creation and a
\function{Remove()} member because of the particular nature of \class{Fact}
related to other types of entity.

Here is an example of usage of \class{Fact} and \class{Template} objects:

\begin{verbatim}
>>> import clips
>>> clips.Reset()
>>> t0 = clips.BuildTemplate("person", """
    (slot name (type STRING))
    (slot age (type INTEGER))
""", "template for a person")
>>> print t0.PPForm()
(deftemplate MAIN::person "template for a person"
   (slot name (type STRING))
   (slot age (type INTEGER)))

>>> f1 = clips.Fact(t0)
>>> f1_slotkeys = f1.Slots.keys()
>>> print f1_slotkeys
<Multifield [<Symbol 'name'>, <Symbol 'age'>]>
>>> f1.Slots['name'] = "Grace"
>>> f1.Slots['age'] = 24
>>> print f1.PPForm()
f-0     (person (name "Grace") (age 24))
>>> clips.PrintFacts()
f-0     (initial-fact)
>>> f1.Assert()
<Fact 'f-1': fact object at 0x00E0CB10>
>>> print f1.Exists()
True
>>> clips.PrintFacts()
f-0     (initial-fact)
f-1     (person (name "Grace") (age 24))
For a total of 2 facts.
>>> f1.Retract()
>>> print f1.Exists()
False
>>> clips.PrintFacts()
f-0     (initial-fact)
For a total of 1 fact.
\end{verbatim}

Please note that slot names are implemented as \class{Symbol}s, and the
list of \var{Slots} is returned as a \class{Multifield}. Also note that
the \class{Fact} \var{f1}, that has been constructed from a
\class{Template} (and not yet \function{Assert}ed) object and then
modified using the \var{Slots} property, can be \function{Assert}ed while
other \class{Fact}s built from construct strings cannot.

\end{classdesc*}



\section{Deffacts\label{pyclips-cl-Deffacts}}

A \class{Deffacts} is used to modify the ``initial structure'' of a CLIPS
environment, by allowing some \class{Fact}s to be \function{Assert}ed by
default each time the \function{Reset()} function is called.

\begin{classdesc*}{Deffacts}

This represents a copy of a \code{deffacts} construct in the CLIPS
subsystem, and not a true \code{deffacts} entity. More than one
\class{Deffacts} object in Python can refer to the same \code{deffacts}
entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Deletable}
Read-only property to verify if this \class{Deffacts} can be deleted.
\end{memberdesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Deffacts} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Read-only property returning the name in CLIPS of this \class{Deffacts}.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Deffacts} in the list of all \class{Deffacts}.
\var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Deffacts}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove the entity corresponding to this \class{Deffacts} from the CLIPS
subsystem.
\end{methoddesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Deffacts} is
\function{BuildDeffacts()}, which has been discussed above.

\end{classdesc*}



\section{Rule\label{pyclips-cl-Rule}}

The construct defines rules to be activated and then \emph{fired} whenever
particular conditions are met. This construct is in fact the counterpart
of the \code{defrule} construct in CLIPS. Normally conditions that fire
\class{Rule}s are \class{Fact}s \function{Assert}ed during a session.

\begin{classdesc*}{Rule}

This represents a copy of a \code{defrule} construct in the CLIPS
subsystem, and not a true \code{defrule} entity. More than one
\class{Rule} object in Python can refer to the same \code{defrule}
entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Breakpoint}
Set or remove a breakpoint from this \class{Rule}.
\end{memberdesc}

\begin{memberdesc}[property]{Deletable}
Read-only property to verify if this \class{Rule} can be deleted.
\end{memberdesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Rule} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Read-only property returning the name in CLIPS of this \class{Rule}.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Rule} in the list of all \class{Rule}s. \var{None} is
returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Rule}.
\end{methoddesc}

\begin{methoddesc}{PrintMatches}{}
Print partial matches of this \class{Rule} to standard output.
\end{methoddesc}

\begin{methoddesc}{Refresh}{}
Refresh this \class{Rule}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove the entity corresponding to this \class{Rule} from the CLIPS
subsystem.
\end{methoddesc}

\begin{memberdesc}[property]{WatchActivations}
Set or reset debugging of \emph{activations} for this \class{Rule}.
\end{memberdesc}

\begin{memberdesc}[property]{WatchFirings}
Set or reset debugging of \emph{firings} for this \class{Rule}.
\end{memberdesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Rule}s is
\function{BuildRule()}, which has been discussed above.

\end{classdesc*}

An example -- derived from the ones present in the standard CLIPS
documentation -- may be useful here:

\begin{verbatim}
>>> clips.Reset()
>>> r1 = clips.BuildRule("duck-rule", "(duck)",
                         "(assert (quack))", "The Duck rule")
>>> print r1.PPForm()
(defrule MAIN::duck-rule "The Duck rule"
   (duck)
   =>
   (assert (quack)))

>>> clips.PrintFacts()
f-0     (initial-fact)
For a total of 1 fact.
>>> clips.PrintRules()
MAIN:
duck-rule
>>> f1 = clips.Assert("(duck)")
>>> clips.PrintAgenda()
MAIN:
   0      duck-rule: f-1
For a total of 1 activation.
>>> clips.PrintFacts()
f-0     (initial-fact)
f-1     (duck)
For a total of 2 facts.
>>> clips.Run()
>>> clips.PrintFacts()
f-0     (initial-fact)
f-1     (duck)
f-2     (quack)
For a total of 3 facts.
\end{verbatim}



\section{Activation\label{pyclips-cl-Activation}}

\class{Rule} \class{Activation}s are only returned by the CLIPS
subsystem, and cannot be created -- thus there is no \emph{factory
function} for these objects. CLIPS provides \class{Activation} objects
to keep the program flow under control.

\begin{classdesc*}{Activation}

This represents a copy of an \code{activation} object in the CLIPS
subsystem, and not a true \code{activation} entity. More than one
\class{Activation} object in Python can refer to the same
\code{activation} entity in the CLIPS subsystem.


\begin{memberdesc}[property]{Name}
Retrieve \class{Activation} name.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Activation} in the list of all \class{Activation}s.
\var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of \class{Activation}.
\end{methoddesc}

\begin{memberdesc}[property]{Salience}
Retrieve \class{Activation} \emph{salience}\footnote{\emph{Salience} is
a value that represents the \emph{priority} of a \code{rule} in CLIPS.}.
\end{memberdesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Activation} from CLIPS.
\end{methoddesc}

The name of this entity in CLIPS is also returned by the string coercion
function.

\end{classdesc*}



\section{Global\label{pyclips-cl-Global}}

\class{Global} objects represent \emph{global variables} in CLIPS, which
are normally built using the \code{defglobal} construct. To define a new
\class{Global} variable the \function{BuildGlobal()} function must be
used, which returns a new object.

\begin{classdesc*}{Global}

A \class{Global} object represents a copy of a \code{defglobal} construct
in the CLIPS subsystem, and not a true \code{defglobal} entity. More
than one \class{Global} object in Python can refer to the same
\code{defglobal} entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Deletable}
Verify if this \class{Global} can be deleted.
\end{memberdesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Global} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Retrieve \class{Global} name. The returned value is a \class{Symbol}
containing the name of the global variable in the CLIPS subsystem.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Global} in the list of all global variables. \var{None}
is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print} form of \class{Global}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Global} from CLIPS subsystem.
\end{methoddesc}

\begin{memberdesc}[property]{Value}
Set or retrieve \class{Global} value. The returned value can be of many
types, depending on the type of value contained in the corresponding
CLIPS global variable.
\end{memberdesc}

\begin{methoddesc}{ValueForm}{}
Return a ``\emph{printed}'' form of \class{Global} value. The
\emph{printed} form is the one that would be used in CLIPS to represent
the variable itself.
\end{methoddesc}

\begin{memberdesc}[property]{Watch}
Set or retrieve \class{Global} debug status.
\end{memberdesc}

Some examples follow to show the use of \class{Global} objects:

\begin{verbatim}
>>> g_x = clips.BuildGlobal("x", 15)
\end{verbatim}

This is equivalent to the CLIPS declaration:

\begin{verbatim}
CLIPS> (defglobal ?*x* = 15)
\end{verbatim}

Some of the \class{Global} methods are illustrated here:

\begin{verbatim}
>>> g_x
<Global 'x': defglobal object at 0x00E09960>
>>> print g_x
x
>>> g_x.Value
<Integer 15>
>>> print g_x.Value
15
>>> print g_x.ValueForm()
?*x* = 15
\end{verbatim}

The name of this entity in CLIPS is also returned by the string coercion
function.

\end{classdesc*}



\section{Function\label{pyclips-cl-Function}}

Objects of this type represent newly defined \emph{functions}
(usually via the CLIPS \code{deffunction} construct) in the CLIPS
subsystem. In fact the \function{BuildFunction()} function described
above, which returns a \class{Function} object, corresponds to the
\code{deffunction} construct.

\begin{classdesc*}{Function}

This represents a copy of a \code{deffunction} construct in the CLIPS
subsystem, and not a true \code{deffunction} entity. More than one
\class{Function} object in Python can refer to the same
\code{deffunction} entity in the CLIPS subsystem.

\begin{methoddesc}{Call}{\optional{*args}}
Call this \class{Function} with the given arguments, if any. If one only
argument is passed and it is a \class{str}, then it is considered a
``list of whitespace separated arguments\footnote{See the syntax for
the toplevel function with the same name.}'' and follows the CLIPS
syntax: in order to pass a single string it has to be explicitly cast
to the \class{String} \emph{wrapper class}. Conversion to \emph{wrapper
classes} is however recommended for all passed arguments.
\end{methoddesc}

\begin{memberdesc}[property]{Deletable}
Verify if this \class{Function} can be deleted.
\end{memberdesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Function} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Retrieve \class{Function} name.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Function} in the list of all CLIPS functions. \var{None}
is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of \class{Function}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Function}.
\end{methoddesc}

\begin{memberdesc}[property]{Watch}
Set or retrieve \class{Function} debug status.
\end{memberdesc}

The name of this entity in CLIPS is also returned by the string coercion
function.

\note{Objects of this class are \emph{callable} themselves using the
syntax \code{object([arg1 [, ... [argN]])}, where the arguments follow
the same rules as in the \function{Call} method.}

\end{classdesc*}



\section{Generic\label{pyclips-cl-Generic}}

\class{Generic}s (in CLIPS called \emph{generic functions}) are similar
to \class{Function}s, but they add \emph{generic programming} capabilities
to the CLIPS system. Python programmers will find them similar to Python
functions, since \emph{overloading} is possible within the corresponding
construct.

Each different implementation (for different argument sets) of a
\emph{generic function} is called a \code{Method}, and the \class{Generic}
class provides several ways to inspect the various \code{Method}s.
\code{Method}s are identified by an \emph{index}.

\begin{classdesc*}{Generic}

This represents a copy of a \code{defgeneric} construct in the CLIPS
subsystem, and not a true \code{defgeneric} entity. More than one
\class{Generic} objects in Python can refer to the same
\code{defgeneric} entity in the CLIPS subsystem.

\begin{methoddesc}{AddMethod}{restrictions, actions\optional{, midx\optional{, comment}}}
Add a \code{Method} to this \class{Generic}. The structure of this
function resembles the one of the \function{Build<entity>()} functions:
in fact this method of \class{Generic} actually implements the
\code{defmethod} construct which is present in CLIPS. For proper
documentation of this construct, see the CLIPS reference: the
\var{restrictions} parameter (which represents the \code{Method}
\emph{parameter restrictions}) must be expressed \emph{without}
parentheses; the \var{actions} parameter must be expressed as in the
\code{defmethod} construct, that is with all the necessary parentheses
pairs. \var{midx} is the \code{Method} index when it has to be forced
(optionally). The example below should be explanatory. \var{restrictions}
can also be expressed as a sequence of tuples, in each of which the
first element is the argument name (with its proper prefix) as a string
and the following ones are the actual restrictions, either in string form
or as CLIPS primitive types -- which can be specified using \pyclips{}
\emph{wrapper classes} types, see above.
\end{methoddesc}

\begin{methoddesc}{Call}{\optional{*args}}
Call this \class{Generic} with the given arguments, if any. If one only
argument is passed and it is a \class{str}, then it is considered a
``list of whitespace separated arguments'' and follows the CLIPS
syntax: in order to pass a single string it has to be explicitly cast
to the \class{String} \emph{wrapper class}. Conversion to \emph{wrapper
classes} is however recommended for all passed arguments.
\end{methoddesc}

\begin{memberdesc}[property]{Deletable}
Verify if this \class{Generic} can be deleted.
\end{memberdesc}

\begin{methoddesc}{InitialMethod}{}
Return the index of first \code{Method} in this \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{MethodDeletable}{midx}
Test whether or not specified \code{Method} can be deleted from this
\class{Generic}.
\end{methoddesc}

\begin{methoddesc}{MethodDescription}{midx}
Return the synopsis of specified \code{Method} \emph{restrictions}.
\end{methoddesc}

\begin{methoddesc}{MethodList}{}
Return the list of \code{Method} indices for this \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{MethodPPForm}{midx}
Return the \emph{pretty-print form} of specified \code{Method}.
\end{methoddesc}

\begin{methoddesc}{MethodRestrictions}{midx}
Return the \emph{restrictions} of specified \code{Method} in this
\class{Generic} object: the \var{midx} parameter must be an
\class{Integer} or \class{int} indicating the \code{Method} index.
\end{methoddesc}

\begin{methoddesc}{MethodWatched}{midx}
Test whether or not specified \code{Method} is being watched.
\end{methoddesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Generic} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Retrieve \class{Generic} name.
\end{memberdesc}

\begin{methoddesc}{NextMethod}{midx}
Return the index of next \code{Method} in this \class{Generic} given
the start index as an \class{Integer} or \class{int}.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{PrintMethods}{}
Print out \code{Method} list for this \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{RemoveMethod}{midx}
Remove specified \code{Method} from this \class{Generic}.
\end{methoddesc}

\begin{methoddesc}{UnwatchMethod}{midx}
Deactivate watch on specified \code{Method}.
\end{methoddesc}

\begin{memberdesc}[property]{Watch}
Set or retrieve \class{Generic} debug status.
\end{memberdesc}

\begin{methoddesc}{WatchMethod}{midx}
Activate watch on specified \code{Method}.
\end{methoddesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Generic}s is
\function{BuildGeneric()}, which has been discussed above.

\note{Objects of this class are \emph{callable} themselves using the
syntax \code{object([arg1 [, ... [argN]])}, where the arguments follow
the same rules as in the \function{Call} method.}

An example for this class follows.

\begin{verbatim}
>>> import clips
>>> addf = clips.BuildGeneric("my-addf", "my generic add function")
>>> addf.AddMethod("(?a STRING)(?b STRING)", "(str-cat ?a ?b)")
>>> addf.AddMethod("(?a INTEGER)(?b INTEGER)", "(+ ?a ?b)")
>>> addf.PrintMethods()
my-addf #1  (STRING) (STRING)
my-addf #2  (INTEGER) (INTEGER)
For a total of 2 methods.
>>> print addf.MethodPPForm(1)
(defmethod MAIN::my-addf
   ((?a STRING)
    (?b STRING))
   (str-cat ?a ?b))

>>> print addf.PPForm()
(defgeneric MAIN::my-addf "my generic add function")

>>> print clips.Eval('(my-addf 5 13)')
18
>>> print clips.Eval('(my-addf "hello,"(my-addf " " "world!"))')
hello, world!
>>> print clips.Eval('(my-addf "hello" 13)')
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in ?
    print clips.Eval('(my-addf "hello" 13)')
  File ".../_clips_wrap.py", line 2472, in Eval
    return _cl2py(_c.eval(expr))
ClipsError: C10: unable to evaluate expression
>>> s = clips.ErrorStream.Read()
>>> print s
[GENRCEXE1] No applicable methods for my-addf.
\end{verbatim}

\end{classdesc*}

Please note how the \emph{error stream} (\var{ErrorStream}) can be used
to retrieve a more explanatory text for the error. The \emph{error
stream} can be very useful during interactive debugging \pyclips{}
sessions to fix errors.



\section{Class\label{pyclips-cl-Class}}

\class{Class} objects are \code{class} definition constructs, the most
important feature of the \emph{COOL}\footnote{Acronym for CLIPS
Object-Oriented Language.} sublanguage of CLIPS. As in other OOP
environments, \code{class}es represent in CLIPS new data types (often
resulting from aggregation of simpler data types) which have particular ways
of being handled. Normally, as in Python, these particular ways are called
\emph{methods}\footnote{Note that the term \code{Method} has been used
for function overloading in the definition of \class{Generic}
functions.}, while in CLIPS they are called \emph{message handlers},
since to apply a method to a CLIPS object (in fact, the \class{Instance}
of a \class{Class} in \pyclips{}) a \emph{message} has to be sent to that
object.

\begin{classdesc*}{Class}

This represents a copy of a \code{defclass} construct in the CLIPS
subsystem, and not a true \code{defclass} entity. More than one
\class{Class} object in Python can refer to the same \code{defclass}
entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Abstract}
Verify if this \class{Class} is \emph{abstract} or not.
\end{memberdesc}

\begin{methoddesc}{AddMessageHandler}{name, args, text \optional{, type, comment}}
Add a new \emph{message handler} to this class, with specified name,
body (the \var{text} argument) and argument list: this can be
specified either as a sequence of variable names or as a single string
of whitespace separated variable names. Variable names (expressed as
strings) can also be \emph{wildcard parameters}, as specified in the
\clipsbpg{}. The \var{type} parameter should be one of \var{AROUND},
\var{AFTER}, \var{BEFORE}, \var{PRIMARY} defined at the module level:
if omitted it will be considered as \var{PRIMARY}. The body must be
enclosed in brackets, as it is in CLIPS syntax. The function returns
the \emph{index} of the \emph{message handler} within this \class{Class}.
\end{methoddesc}

\begin{methoddesc}{AllMessageHandlerList}{}
Return the list of \code{MessageHandler} constructs of this \class{Class}
including the ones that have been inherited from the superclass.
\end{methoddesc}

\begin{methoddesc}{BuildInstance}{name, \optional{overrides}}
Build an \class{Instance} of this \class{Class} with the supplied name
and overriding specified \code{slots}. If no \code{slot} is specified
to be overridden, then the \class{Instance} will assume default values.
\end{methoddesc}

\begin{methoddesc}{BuildSubclass}{name, text \optional{, comment}}
Build a subclass of this \class{Class} with specified name and body.
\var{comment} is the optional comment to give to the object.
\end{methoddesc}

\begin{memberdesc}[property]{Deletable}
Verify if this \class{Class} can be deleted.
\end{memberdesc}

\begin{methoddesc}{Description}{}
Return a summary of \class{Class} description.
\end{methoddesc}

\begin{methoddesc}{InitialInstance}{}
Return initial \class{Instance} of this \class{Class}. It raises an
error if the \class{Class} has no subclass \class{Instance}s.
\end{methoddesc}

\begin{methoddesc}{InitialSubclassInstance}{}
Return initial instance of this \class{Class} including its subclasses. It
raises an error if the \class{Class} has no subclass \class{Instance}s.
\end{methoddesc}

\begin{methoddesc}{IsSubclassOf}{o}
Test whether this \class{Class} is a subclass of specified \class{Class}.
\end{methoddesc}

\begin{methoddesc}{IsSuperclassOf}{o}
Test whether this \class{Class} is a superclass of specified
\class{Class}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerDeletable}{index}
Return true if specified \code{MessageHandler} can be deleted.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerIndex}{name \optional{, htype}}
Find the specified \code{MessageHandler}, given its \var{name} and type
(as the parameter \var{htype}). If type is omitted, it is considered to
be \var{PRIMARY}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerName}{index}
Return the name of specified \code{MessageHandler}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerList}{}
Return the list of \code{MessageHandler} constructs for this
\class{Class}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerPPForm}{index}
Return the \emph{pretty-print form} of \code{MessageHandler}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerType}{index}
Return the type of the \code{MessageHandler} specified by the provided
\var{index}.
\end{methoddesc}

\begin{methoddesc}{MessageHandlerWatched}{index}
Return watch status of specified \code{MessageHandler}.
\end{methoddesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Class} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Retrieve \class{Class} name.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Class} in the list of all CLIPS \code{classes}.
\var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{NextInstance}{instance}
Return next \class{Instance} of this \class{Class}. Returns \var{None} if
there are no \class{Instance}s left.
\end{methoddesc}

\begin{methoddesc}{NextMessageHandlerIndex}{index}
Return index of next \code{MessageHandler} with respect to the specified
one.
\end{methoddesc}

\begin{methoddesc}{NextSubclassInstance}{instance}
Return next instance of this \class{Class}, including subclasses. Returns
\var{None} if there are no \class{Instance}s left.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of \class{Class}.
\end{methoddesc}

\begin{methoddesc}{PreviewSend}{msgname}
Print list of \code{MessageHandler}s suitable for specified message.
\end{methoddesc}

\begin{methoddesc}{PrintAllMessageHandlers}{}
Print the list of all \code{MessageHandler}s for this \class{Class}
including the ones that have been inherited from the superclass.
\end{methoddesc}

\begin{methoddesc}{PrintMessageHandlers}{}
Print the list of \code{MessageHandler}s for this \class{Class}.
\end{methoddesc}

\begin{methoddesc}{RawInstance}{name}
Create an empty \class{Instance} of this \class{Class} with specified
name.
\end{methoddesc}

\begin{memberdesc}[property]{Reactive}
Verify if this \class{Class} is \emph{reactive} or not.
\end{memberdesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Class}.
\end{methoddesc}

\begin{methoddesc}{RemoveMessageHandler}{index}
Remove \code{MessageHandler} specified by the provided \var{index}.
\end{methoddesc}

\begin{memberdesc}[property]{Slots}
\class{Class} \code{slots} information. This is itself an object, having
many methods, and deserves a special explaination.
\begin{methoddesc}{AllowedClasses}{name}
Return a list of allowed class names for \code{slot} specified by
\var{name}.
\end{methoddesc}
\begin{methoddesc}{AllowedValues}{name}
Return a list of allowed values for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{Cardinality}{name}
Return \emph{cardinality} for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{DefaultValue}{name}
Return the default value for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{Exists}{name}
Return \constant{True} if \code{slot} specified by \var{name} exists,
\constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{ExistsDefined}{name}
Return \constant{True} if \code{slot} specified by \var{name} is defined
in this \class{Class}, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{Facets}{name}
Return \emph{facet names} for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{HasDirectAccess}{name}
Return \constant{True} if \code{slot} specified by \var{name} is directly
accessible, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{IsInitable}{name}
Return \constant{True} if \code{slot} specified by \var{name} is
\emph{initializable}, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{IsPublic}{name}
Return \constant{True} if \code{slot} specified by \var{name} is
\emph{public}, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{IsWritable}{name}
Return \constant{True} if \code{slot} specified by \var{name} is
\emph{writable}, \constant{False} otherwise.
\end{methoddesc}
\begin{methoddesc}{Names}{}
Return the list of \code{slot} names.
\end{methoddesc}
\begin{methoddesc}{NamesDefined}{}
Return the list of \code{slot} names explicitly defined in this
\class{Class}.
\end{methoddesc}
\begin{methoddesc}{Range}{name}
Return \emph{numerical range information} for \code{slot} specified by
\var{name}.
\end{methoddesc}
\begin{methoddesc}{Sources}{name}
Return \emph{source class names} for \code{slot} specified by \var{name}.
\end{methoddesc}
\begin{methoddesc}{Types}{name}
Return names of \emph{primitive types} for \code{slot} specified by
\var{name}.
\end{methoddesc}
\end{memberdesc}

\begin{methoddesc}{Subclasses}{}
Return the names of subclasses of this \class{Class}.
\end{methoddesc}

\begin{methoddesc}{Superclasses}{}
Return the names of superclasses of this \class{Class}.
\end{methoddesc}

\begin{methoddesc}{UnwatchMessageHandler}{index}
Turn off debug for specified \code{MessageHandler}.
\end{methoddesc}

\begin{memberdesc}[property]{WatchInstances}
Set or retrieve debug status for this \class{Class} \class{Instance}s.
\end{memberdesc}

\begin{methoddesc}{WatchMessageHandler}{index}
Turn on debug for specified \code{MessageHandler}.
\end{methoddesc}

\begin{memberdesc}[property]{WatchSlots}
Set or retrieve \code{Slot} debug status.
\end{memberdesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Class}es is
\function{BuildClass()}, which has been discussed above.

\end{classdesc*}



\section{Instance\label{pyclips-cl-Instance}}

\class{Instance} objects represent \emph{class instances} (that is,
\emph{objects} in the OOP paradigm) that live in the CLIPS subsystem.
Messages can be sent to those objects and values can be set and retrieved
for the \emph{slots} defined in the related \emph{class}, where the
meaning of \code{slot} has been described in the section above.

\begin{classdesc*}{Instance}

This represents a copy of an \code{instance} object in the CLIPS
subsystem, and not a true \code{instance} entity. More than one
\class{Instance} object in Python can refer to the same \code{instance}
entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Class}
Retrieve the \class{Class} of this \class{Instance}: this property
actually refers to a \class{Class} object, so all of its methods are
available.
\end{memberdesc}

\begin{methoddesc}{DirectRemove}{}
Directly remove this \class{Instance}, without sending a message.
\end{methoddesc}

\begin{methoddesc}{GetSlot}{slotname}
Retrieve the value of \code{Slot} specified as argument. The synonym
\function{SlotValue} is retained for readability and compatibility.
Please notice that these functions are provided in order to be more
coherent with the behaviour of CLIPS API, as CLIPS C interface users
know that a function like \function{GetSlot} usually bypasses message
passing, thus accessing \code{slots} directly. The possibilities
offered by \function{GetSlot} are also accessible using the \var{Slots}
property described below.
\end{methoddesc}

\begin{methoddesc}{IsValid}{}
Determine if this \class{Instance} is still valid.
\end{methoddesc}

\begin{memberdesc}[property]{Name}
Retrieve the \class{Instance} name.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Instance} in the list of all CLIPS \code{instances}.
It returns \var{None} if there are no \class{Instance}s left.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of \class{Instance}.
\end{methoddesc}

\begin{methoddesc}{PutSlot}{slotname, value}
Set the value of specified \code{slot}. The \var{value} parameter should
contain a value of the correct type, if necessary cast to one of the
\emph{wrapper classes} described above if the type could be ambiguous.
The synonym \function{SetSlotValue} is provided for readability and
compatibility. What has been said about \function{GetSlot} also yields
for the hereby described function, as the possibilities offered by
\function{PutSlot} are also accessible using the \var{Slots} property
described below.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Remove this \class{Instance} (passing a message).
\end{methoddesc}

\begin{methoddesc}{Send}{msg \optional{, args}}
Send the provided \emph{message} with the given arguments to
\class{Instance}. The \var{args} parameter (that is, \emph{message
arguments}), should be a string containing a list of arguments
separated by whitespace, a tuple containing the desired arguments or a
value of a basic type. Also in the second case the tuple elements have
to be of basic types. The function returns a value depending on the
passed message.
\end{methoddesc}

\begin{memberdesc}[property]{Slots}
Dictionary of \class{Instance} \code{slots}. This member \emph{behaves}
like a \class{dict}, but is not related to such objects. In fact, the
values of \code{slots} are accessible using a \class{dict}-like syntax
(square brackets), but not all the members of \class{dict} are
implemented. The functionality of \function{PutSlot} and
\function{GetSlot} is superseded by this property.
\end{memberdesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Instance}s is
\function{BuildInstance()}, which has been discussed above.

Here is an example of usage of \class{Instance} and \class{Class} objects:

\begin{verbatim}
>>> import clips
>>> clips.Build("""(defclass TEST1
    (is-a USER)
    (slot ts1 (type INSTANCE-NAME))
    (multislot ts2))""")
>>> c = clips.FindClass("TEST1")
>>> print c.PPForm()
(defclass MAIN::TEST1
   (is-a USER)
   (slot ts1
      (type INSTANCE-NAME))
   (multislot ts2))

>>> clips.Reset()
>>> i = clips.BuildInstance("test1", c)
>>> i.Slots['ts2'] = clips.Multifield(['hi', 'there'])
>>> i.Slots['ts1'] = i.Name
>>> print i.PPForm()
[test1] of TEST1 (ts1 [test1]) (ts2 "hi" "there")
\end{verbatim}

\end{classdesc*}



\section{Definstances\label{pyclips-cl-Definstances}}

As there are \code{deffacts} for \code{fact} objects, \code{instances}
are supported in CLIPS by the \code{definstances} construct: it allows
certain default \class{Instance}s to be created each time a
\function{Reset()} is issued. In \pyclips{} this construct is provided
via the \class{Definstances} class.

\begin{classdesc*}{Definstances}

This represents a copy of the \code{definstances} construct in the CLIPS
subsystem, and not a true \code{definstances} entity. More than one
\class{Definstances} object in Python can refer to the same
\code{definstances} entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Deletable}
Verify if this \class{Definstances} can be deleted.
\end{memberdesc}

\begin{memberdesc}[property]{Module}
Read-only property to retrieve the CLIPS name of the \class{Module}
where the \class{Definstances} is defined.
\end{memberdesc}

\begin{memberdesc}[property]{Name}
Retrieve \class{Definstances} name.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Definstances} in the list of all CLIPS
\code{definstances}. \var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Definstances} object.
\end{methoddesc}

\begin{methoddesc}{Remove}{}
Delete this \class{Definstances} object from CLIPS subsystem.
\end{methoddesc}

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Definstances} is
\function{BuildDefinstances()}, which has been discussed above.

\end{classdesc*}



\section{Module\label{pyclips-cl-Module}}

\class{Module}s are a way, in CLIPS, to organize constructs, facts and
objects. There is a big difference between \emph{modules} and
\emph{environments}\footnote{Besides the discussion above, also notice
that in a ``pure'' CLIPS session there is no concept of \emph{environment}
at all: the use of environment is reserved to those who embed CLIPS in
another program, such as \pyclips{} users.}: one should think of a
\class{Module} as a \emph{group} of definitions and objects, which can
interoperate with entities that are defined in other \class{Module}s. The
\class{Module} class provides methods, similar to the ones defined at top
level, to directly create entities as part of the \class{Module} itself,
as well as methods to examine \class{Module} contents. Also,
\class{Module} objects have methods that instruct the related CLIPS
\code{module} to become \emph{current}, so that certain operations can
be performed without specifying the \code{module} to which they have to
be applied.

\begin{classdesc*}{Module}

This represents a copy of a \code{defmodule} construct in the CLIPS
subsystem, and not a true \code{defmodule} entity. More than one
\class{Module} object in Python can refer to the same \code{defmodule}
entity in the CLIPS subsystem.

\begin{memberdesc}[property]{Name}
Return the name of this \class{Module}.
\end{memberdesc}

\begin{methoddesc}{Next}{}
Return next \class{Module} in the list of all CLIPS \code{modules}.
\var{None} is returned at the end of the list.
\end{methoddesc}

\begin{methoddesc}{PPForm}{}
Return the \emph{pretty-print form} of this \class{Module}.
\end{methoddesc}

\begin{methoddesc}{SetCurrent}{}
Make the \code{module} that this object refers the current \class{Module}.
\end{methoddesc}

\begin{methoddesc}{SetFocus}{}
Set focus to this \class{Module}.
\end{methoddesc}

For the following methods:
\begin{verbatim}
TemplateList(), FactList(), DeffactsList(), ClassList(), DefinstancesList(),
GenericList(), FunctionList(), GlobalList(), BuildTemplate(),
BuildDeffacts(), BuildClass(), BuildDefinstances(), BuildGeneric(),
BuildFunction(), BuildGlobal(), BuildRule(), BuildInstance(),
PrintTemplates(), PrintDeffacts(), PrintRules(), PrintClasses(),
PrintInstances(), PrintSubclassInstances(), PrintDefinstances(),
PrintGenerics(), PrintFunctions(), PrintGlobals(), ShowGlobals(),
PrintAgenda(), PrintBreakpoints(), ReorderAgenda(), RefreshAgenda()
\end{verbatim}

please refer to the corresponding function defined at module level,
keeping in mind that these methods perform the same task but within the
\class{Module} where they are executed.

The name of this entity in CLIPS is also returned by the string coercion
function. The \emph{factory function} for \class{Module}s is
\function{BuildModule()}, which has been discussed above.

\end{classdesc*}



\section{Environment\label{pyclips-cl-Environment}}

This class represents an \emph{environment}, and implements almost all
the module level functions and classes. The only objects appearing at
\pyclips{} level and \emph{not} at \class{Environment} level are the
CLIPS I/O subsystem \emph{streams}, which are shared with the rest of
the CLIPS engine.

\class{Environment} objects are not a feature of CLIPS sessions (as
stated above), thus there is no way to identify them in CLIPS using
a \emph{symbol}. So \class{Environment} objects do not have a \var{Name}
property. Instead, CLIPS provides a way to identify an
\emph{environment} through an integer called \emph{index}.

\begin{classdesc*}{Environment}

Please refer to top level functions, variables and classes for
information on contents of \class{Environment} objects. The extra
methods and properties follow below.

\begin{memberdesc}[property]{Index}
Retrieve the \emph{index} identifying this \class{Environment}
internally in CLIPS.
\end{memberdesc}

\begin{methoddesc}{SetCurrent}{}
Make the \emph{environment} that this object refers the current
\class{Environment}.
\end{methoddesc}

Further explanations about \class{Environment} objects can be found
in the appendices.

\end{classdesc*}



\section{Status and Configuration Objects\label{pyclips-cl-statusconf}}

As seen in the introduction, there are a couple of objects that can be
accessed to configure the underlying CLIPS engine and to retrieve its
status. These are the \var{EngineConfig} and \var{DebugConfig} objects.
The reason why configuration and status functions have been grouped in
these objects is only cosmetic: in fact there is no counterpart of
\var{EngineConfig} and \var{DebugConfig} in CLIPS. It was seen as convenient
to group configuration and debug functions in two main objects and to
make them accessible mainly as \emph{properties} in Python, instead of
populating the module namespace with too many \emph{get/set} functions.

There is also an object, called \var{Memory}, which gives information
about memory utilization and allow the user to attempt to free memory
used by the CLIPS engine and no longer needed.

A description of what the above objects (which can not be instanced by
the user of \pyclips{}\footnote{Besides removal of class definitions, a
\emph{singleton}-styled implementation mechanism prevents the user from
creating further instances of the objects.}) actually expose follows.


\subsection{Engine Configuration\label{pyclips-cl-statusconf-engine}}

The \var{EngineConfig} object allows the configuration of some features
of the underlying CLIPS engine. Here are the properies provided by
\var{EngineConfig}:

\begin{memberdesc}[property]{AutoFloatDividend}
Reflects the behaviour of CLIPS \code{get/set-auto-float-dividend}. When
\constant{True} the dividend is always considered to be a floating point
number within divisions.
\end{memberdesc}

\begin{memberdesc}[property]{ClassDefaultsMode}
Reflects the behaviour of CLIPS \code{get/set-class-defaults-mode}.
Possible values of this flag are \constant{CONVENIENCE_MODE} and
\constant{CONSERVATION_MODE}. See \clipsapg{} for details.
\end{memberdesc}

\begin{memberdesc}[property]{DynamicConstraintChecking}
Reflects the behaviour of CLIPS \code{get/set-dynamic-constraint-checking}.
When \constant{True}, \emph{function calls} and \emph{constructs} are
checked against constraint violations.
\end{memberdesc}

\begin{memberdesc}[property]{FactDuplication}
Reflects the behaviour of CLIPS \code{get/set-fact-duplication}. When
\constant{True}, \code{facts} can be reasserted when they have already
been asserted\footnote{This does not change the behaviour of the
\class{Fact} class, which prohibits reassertion anyway. However,
\code{facts} that would be asserted through firing of rules and would
generate duplications will not raise an error when this behaviour is
set.}.
\end{memberdesc}

\begin{memberdesc}[property]{IncrementalReset}
Reflects the behaviour of CLIPS \code{get/set-incremental-reset}. When
\constant{True} newly defined \code{rules} are updated according to
current \code{facts}, otherwise new \code{rules} will only be updated by
\code{facts} defined after their construction.
\end{memberdesc}

\begin{memberdesc}[property]{ResetGlobals}
Reflects the behaviour of CLIPS \code{get/set-reset-globals}. When
\constant{True} the \class{Global} variables are reset to their initial
value after a call to \function{Reset()}.
\end{memberdesc}

\begin{memberdesc}[property]{SalienceEvaluation}
Reflects the behaviour of CLIPS \code{get/set-salience-evaluation}. Can
be one of \constant{WHEN_DEFINED}, \constant{WHEN_ACTIVATED},
\constant{EVERY_CYCLE}. See the previous chapter and \clipsapg{} for
more information.
\end{memberdesc}

\begin{memberdesc}[property]{SequenceOperatorRecognition}
Reflects the behaviour of CLIPS
\code{get/set-sequence-operator-recognition}. When \constant{False},
\class{Multifield} values in function calls are treated as a single
argument.
\end{memberdesc}

\begin{memberdesc}[property]{StaticConstraintChecking}
Reflects the behaviour of CLIPS \code{get/set-static-constraint-checking}.
When \constant{True}, \emph{slot values} are checked against constraint
violations.
\end{memberdesc}

\begin{memberdesc}[property]{Strategy}
Reflects \code{get/set-strategy} behaviour. Can be any of the following
values: \constant{RANDOM_STRATEGY}, \constant{LEX_STRATEGY},
\constant{MEA_STRATEGY}, \constant{COMPLEXITY_STRATEGY},
\constant{SIMPLICITY_STRATEGY}, \constant{BREADTH_STRATEGY} or
\constant{DEPTH_STRATEGY}. See the previous chapter and \clipsapg{} for
more information.
\end{memberdesc}


\subsection{Debug Settings\label{pyclips-cl-statusconf-debug}}

The \var{DebugConfig} object provides access to the debugging and trace
features of CLIPS. During a CLIPS interactive session debug and trace
messages are printed on the system console (which maps the \code{wtrace}
I/O \emph{router}). Users of the trace systems will have to poll the
\var{TraceStream} to read the generated messages.

In CLIPS, the process of enabling trace features on some class of
entities is called \emph{to watch} such a class; this naming convention
is reflected in \pyclips{}. Note that specific objects can be
\emph{watched}: many classes have their own \var{Watch} property to
enable or disable debugging on a particular object.

Also, CLIPS provides a facility to log all debug information to physical
files: this is called \emph{to dribble} on a file. \emph{Dribbling} is
possible from \var{DebugConfig} via the appropriate methods.

The names of methods and properties provided by this object are quite
similar to the corresponding commands in CLIPS, so more information
about debugging features can be found in \clipsbpg{}.

\begin{memberdesc}[property]{ActivationsWatched}
Flag to enable or disable trace of \class{Rule} activations and
deactivations.
\end{memberdesc}

\begin{memberdesc}[property]{CompilationsWatched}
Flag to enable or disable trace of construct definition progress.
\end{memberdesc}

\begin{methoddesc}{DribbleActive}{}
Tell whether or not \emph{dribble} is active.
\end{methoddesc}

\begin{methoddesc}{DribbleOff}{}
Turn off \emph{dribble} and close the \emph{dribble} file.
\end{methoddesc}

\begin{methoddesc}{DribbleOn}{fn}
Enable \emph{dribble} on the file identified by provided filename
\var{fn}.
\end{methoddesc}

\begin{memberdesc}[property]{ExternalTraceback}
Flag to enable or disable printing traceback messages to Python
\var{sys.stderr} if an error occurs when the CLIPS engine calls a
Python function. Please note that the error is not propagated to the
Python interpreter. See the appendices for a more detailed explaination.
\end{memberdesc}

\begin{memberdesc}[property]{FactsWatched}
Flag to enable or disable trace of \class{Fact} assertions and
retractions.
\end{memberdesc}

\begin{memberdesc}[property]{FunctionsWatched}
Flag to enable or disable trace of start and finish of \class{Functions}.
\end{memberdesc}

\begin{memberdesc}[property]{GenericFunctionsWatched}
Flag to enable or disable trace of start and finish of \class{Generic}
functions.
\end{memberdesc}

\begin{memberdesc}[property]{GlobalsWatched}
Flag to enable or disable trace of assignments to \class{Global}
variables.
\end{memberdesc}

\begin{memberdesc}[property]{MethodsWatched}
Flag to enable or disable trace of start and finish of \code{Methods}
within \class{Generic} functions.
\end{memberdesc}

\begin{memberdesc}[property]{MessageHandlersWatched}
Flag to enable or disable trace of start and finish of
\code{MessageHandlers}.
\end{memberdesc}

\begin{memberdesc}[property]{MessagesWatched}
Flag to enable or disable trace of start and finish of \emph{messages}.
\end{memberdesc}

\begin{memberdesc}[property]{RulesWatched}
Flag to enable or disable trace of \class{Rule} firings.
\end{memberdesc}

\begin{memberdesc}[property]{SlotsWatched}
Flag to enable or disable trace of changes to \class{Instance}
\code{Slots}.
\end{memberdesc}

\begin{memberdesc}[property]{StatisticsWatched}
Flag to enable or disable reports about timings, number of \code{facts}
and \code{instances}, and other information after \function{Run()} has
been performed.
\end{memberdesc}

\begin{methoddesc}{UnwatchAll}{}
Turn off \emph{watch} for all items above.
\end{methoddesc}

\begin{methoddesc}{WatchAll}{}
\emph{Watch} all items above.
\end{methoddesc}

\note{Other CLIPS I/O streams besides \var{TraceStream} can be involved
in the trace process: please refer to the CLIPS guides for details.}


\subsection{Memory Operations\label{pyclips-cl-statusconf-memory}}

This object provides access to the memory management utilities of the
underlying CLIPS engine. As said above, it allows the reporting of memory
usage and the attempt to free memory that is used not for computational
purposes. Also, a property of this object affects the engine behaviour
about whether or not to cache some information. Here is what the object
exposes:

\begin{memberdesc}[property]{Conserve}
When set to \constant{True}, the engine does not cache \emph{pretty-print
forms} to memory, thus being more conservative.
\end{memberdesc}

\begin{memberdesc}[property]{EnvironmentErrorsEnabled}
When set to \constant{True}, the engine is enabled to directly write
fatal environment errors to the console (\constant{stderr}). This kind
of messages is in most of the cases printed when the program exits, so
it can be annoying. The behaviour is disabled by default.
\end{memberdesc}

\begin{methoddesc}{Free}{}
Attempt to free as much memory as possible of the one used by the
underlying CLIPS engine for previous computations.
\end{methoddesc}

\begin{memberdesc}[property]{PPBufferSize}
Report the size (in bytes) of the buffers used by \pyclips{} to return
\emph{pretty-print forms} or similar values. By default this is set to
8192, but the user can modify it using values greater than or equal to
256. Greater values than the default can be useful when such forms are
used to reconstruct CLIPS entities and definitions are so complex that
the default buffer size is insufficient.
\end{memberdesc}

\begin{memberdesc}[property]{Requests}
Read-only property reporting the number of memory request made by the
engine to the operating system since \pyclips{} has been initialized.
\end{memberdesc}

\begin{memberdesc}[property]{Used}
Read-only property reporting the amount, in kilobytes, of memory used by
the underlying CLIPS engine.
\end{memberdesc}

\begin{memberdesc}[property]{NumberOfEnvironments}
Read-only property reporting the number of currently allocated
\class{Environment}s.
\end{memberdesc}


\section{I/O Streams\label{pyclips-cl-iostreams}}

In order to be more embeddable, CLIPS defines a clear way to redirect its
messages to locations where they can be easily retrieved. CLIPS users can
access these locations for reading or writing by specifying them as
\emph{logical names} (namely \code{stdin}, \code{stdout}, \code{wtrace},
\code{werror}, \code{wwarning}, \code{wdialog}, \code{wdisplay},
\code{wprompt})\footnote{CLIPS also defines \code{t} as a \emph{logical
name}: as stated in \clipsapg{} this indicates \code{stdin} in functions
that read text and \code{stdout} in function that print out. In
\pyclips{}, for all functions that print out to \code{t} the user must
read from \emph{StdoutStream}.}. \pyclips{} creates some special unique
objects\footnote{\pyclips{} in fact defines one more I/O stream, called
\code{temporary}, which is used internally to retrieve output from CLIPS
that shouldn't go anywhere else. \pyclips{} users however are not supposed
to interact with this object.}, called \emph{I/O streams} throughout this
document, to allow the user to read messages provided by the underlying
engine. Most of these objects have only one method, called \function{Read()},
that consumes CLIPS output and returns it as a string: this string contains
all output since a previous call or module initialization. The only exception
is \var{StdinStream} whose single method is \function{Write()} and it
accepts a string\footnote{The current implementation converts the
argument to a string, so other types can be accepted.} as parameter. As
CLIPS writes line-by-line, the string resulting from a call to
\function{Read()} can contain newline characters, often indicating
subsequent messages.

Here is a list of the \emph{I/O streams} provided by \pyclips{}, along
with a brief description of each.

\begin{tableii}{l|l}{var}{Stream}{Description}
	\lineii{StdoutStream}{where information is usually printed out
            (eg. via \code{(printout t ...)})}
	\lineii{TraceStream}{where trace information (see \emph{watch})
            goes}
	\lineii{ErrorStream}{where CLIPS error messages are written in
            readable form}
	\lineii{WarningStream}{where CLIPS warning messages are written
            in readable form}
	\lineii{DialogStream}{where CLIPS informational messages are
            written in readable form}
	\lineii{DisplayStream}{where CLIPS displays information (eg.
            the output of the \code{(facts)} command)}
	\lineii{PromptStream}{where the CLIPS prompt (normally
            \code{CLIPS>}) is sent}
	\lineii{StdinStream}{where information is usually read by CLIPS
            (eg. via \code{(readline)})}
\end{tableii}

Some of the provided \emph{I/O streams} are actually not so relevant for
\pyclips{} programmers: for instance, it is of little use to read the
contents of \var{PromptStream} and \var{DisplayStream}. In the latter
case, in fact, there are other inspection functions that provide the
same information in a more structured way than text. However they are
available to provide a closer representation of the programming interface
and allow CLIPS programmers to verify if the output of \emph{CLIPS-oriented}
calls (see the paragraph about \function{Build()} and \function{Eval()}
in the appendices) really do what they are expected to.



\section{Predefined \class{Class}es\label{pyclips-cl-stockclasses}}

\pyclips{} defines\footnote{At the module level only: defining these
objects at the \emph{environment} level could cause aliasing current
CLIPS enviroment. On the other hand, if these objects were implemented in
a way that checked for aliasing, access to the actual entities would be
surely slower only favouring compactness of user code.}, some \class{Class}
objects, that is the ones that are present in CLIPS itself by default. They
are defined in order to provide a compact access to CLIPS ``stock'' classes:
most of these objects are of little or no use generally (although they
can be handy when testing for class specification or generalization), but
at least one (\var{USER_CLASS}) can be used to make code more readable.

Namely, these \class{Class}es are:

\begin{tableii}{l|l}{var}{Python Name}{CLIPS defclass}
	\lineii{FLOAT_CLASS}{FLOAT}
	\lineii{INTEGER_CLASS}{INTEGER}
	\lineii{SYMBOL_CLASS}{SYMBOL}
	\lineii{STRING_CLASS}{STRING}
	\lineii{MULTIFIELD_CLASS}{MULTIFIELD}
	\lineii{EXTERNAL_ADDRESS_CLASS}{EXTERNAL-ADDRESS}
	\lineii{FACT_ADDRESS_CLASS}{FACT-ADDRESS}
	\lineii{INSTANCE_ADDRESS_CLASS}{INSTANCE-ADDRESS}
	\lineii{INSTANCE_NAME_CLASS}{INSTANCE-NAME}
	\lineii{OBJECT_CLASS}{OBJECT}
	\lineii{PRIMITIVE_CLASS}{PRIMITIVE}
	\lineii{NUMBER_CLASS}{NUMBER}
	\lineii{LEXEME_CLASS}{LEXEME}
	\lineii{ADDRESS_CLASS}{ADDRESS}
	\lineii{INSTANCE_CLASS}{INSTANCE}
	\lineii{INITIAL_OBJECT_CLASS}{INITIAL-OBJECT}
	\lineii{USER_CLASS}{USER}
\end{tableii}

The following code, shows how to use the ``traditional''
\function{BuildClass()} factory function and how to directly subclass one
of the predefined \class{Class} object. In the latter case, probably, the
action of subclassing is expressed in a more clear way:

\begin{verbatim}
>>> import clips
>>> C = clips.BuildClass("C", "(is-a USER)(slot s)")
>>> print C.PPForm()
(defclass MAIN::C
   (is-a USER)
   (slot s))

>>> D = clips.USER_CLASS.BuildSubclass("D", "(slot s)")
>>> print D.PPForm()
(defclass MAIN::D
   (is-a USER)
   (slot s))
\end{verbatim}

Although it actually does not save typing (the statement is slightly
longer), the second form can be used to produce more readable Python code.

\note{These objects are actually useful \emph{only} when the package is
fully imported, that is using the \code{import clips} form: importing
the symbols at global level (in the form \code{from clips import *}) does
in fact create some namespace problems. Since in the latter case the names
that represent stock classes are only references to the ones defined at
module level, \pyclips{} cannot change them when the actual classes are
relocated in the CLIPS memory space, for instance when \function{Clear}
is called.}
