API Reference
Curated, task-grouped mirror of __all__ + the API stability statement + the term hierarchy.
API stability
The surfaces you build programs with are stable: the program verbs
(fact, when, forbid, choose, solve, optimize, and their
relatives), the result types they return, and the predicate-declaration
surface. The hierarchy types block is exported so your
annotations work, and carries weaker guarantees: these appear in public
signatures and return types — annotate with them; you rarely construct them
directly. Docstrings are the per-symbol source of truth; this page is the
map, not the territory. Changes land version by version in the
changelog.
The sections below mirror the categories of aspalchemy.__all__, in order.
Each entry is one line — when you reach for this — plus a link to the guide
section that teaches it.
The program and its results
ASPProgram— the program you build and solve: every verb hangs off it. Taught end to end in Your First Program; the verbs are cataloged in Statements and Terms.Segment— a named slice of a program for organizing large builds; every building verb also lives on a segment. Organizing output.When— the builderwhen(...)returns; close it withderive(),choose(),forbid(),require(), orpenalize(). Rules: when().derive().GroundedProgram—ground()’s immutable snapshot, for asking many questions of one grounding (assumptions, lazy verbs, inspection). Ground once, solve many.SignatureGrounding— one row ofgrounding_profile(): a signature’s ground-atom count and the Python lines that derive it. Profiling grounding.StatementGrounding— one row ofstatement_profile(): a statement’s ground instantiation count and its authoring line; constraints included. Profiling by statement.RecursiveComponent— one row ofrecursion_profile(): signatures whose derivations depend on each other, the statements in the cycle, and whether the recursion passes through negation. Profiling recursion.SolveResult— the lazy, unbounded model streamsolve()returns; iterate it, or takefirst(). The model stream.Model— one answer set; read typed atoms out withatoms(Cls). Reading models.CostedModel— a model paired with its cost, emitted byoptimize_iter()as the search descends. Optimization.AtomCollection— the shared typed-atom reading surface behind models and consequences; subclasses say what their atoms mean. Reading models.Consequences— the common shape of brave/cautious answers: the atoms,.path(every approximation),.complete(proof of exhaustion). Brave and cautious.BraveConsequences—brave()’s answer: what is possible — atoms true in at least one answer set. Brave and cautious.CautiousConsequences—cautious()’s answer: what is certain — atoms true in every answer set. Brave and cautious.RefinementSteps— the lazy handle frombrave_iter()/cautious_iter(): successive approximations, break when satisfied. Brave and cautious.OptimizeSteps— the lazy handle fromoptimize_iter(): each improvement as it is found, every one a real solution. Optimization.Optimum—optimize()’s answer: the best model found, its cost, and.proven— whether optimality was proved or the search was cut short. Optimization.OptStrategy— how the optimizer searches:BB(branch and bound, the default, anytime) orUSC(unsatisfiable cores, often faster on hard optima). Optimization.Search— the abstract lifecycleSolveResult,RefinementSteps, andOptimizeStepsshare (close(),with-blocks, the finalized flags); annotate with it to accept any handle.LogLevel— clingo message severities;stop_on_log_level=sets how loud a message must be to abort. Clingo’s messages.ClingoMessage— one structured clingo diagnostic, carrying its severity and the “generated by file:line” pointer back to your source. Clingo’s messages.ASPAlchemyError— the root of ASPAlchemy’s dedicated exceptions; validation and misuse failures deliberately stay on Python builtins. Errors that teach.GroundingError— clingo rejected the rendered program; the message and.messagescarry the diagnostics, each mapped to the authoring Python line. Clingo’s messages.UnsatisfiableError— no answer set where one was required (first()and the eager verbs);.unsat_corecarries the conflicting assumptions when there are any. Unsat cores.RenderedLine— one line ofSegment.render_lines()output: the text plus the element that produced it (Nonefor framing lines). Seeing the ASP.
Source locations
All five are taught in Source locations.
SourceLocation— the file:line record every statement is stamped with; what diagnostics andrender(annotate=True)display.capture_location()— grab the current user-code location explicitly, to hand tolocation_override()later.register_skip_package()— declare a package (or dotted module prefix) as plumbing, so statements it emits attribute to its callers.attribute_to_caller— decorator for one helper function that emits rules on its caller’s behalf.location_override()— context manager attributing everything built in the block to a location you captured earlier, for code with no honest stack frame.
Declaring predicates
Predicate— the base class every predicate extends; alsoPredicate.define()for runtime-built schemas. Declaring predicates and Dynamic predicates.NegatedSignature— what-Pon a predicate class builds: a declaration of the classically negated signature, forraw_asp()’spredicates=seatbelt. The predicates= seatbelt.Field— typed field annotations:Field[int],Field[str],Field[SomePredicate]; validated writes, plain typed reads. Declaring predicates.PredicateArg— the “any predicate argument” union; the polymorphic field is spelledField[PredicateArg], so every field is aField[...]. It reads plain like any field, but skips the ground-type gate and static narrowing — it reads as the value union, not a specific ground type (it still validates int range, string content, and rejects bool/tuple). Declaring predicates.
Rule-building objects
Variable— an ASP variable; supports arithmetic, comparisons, and.in_(pool)binding. Variables.ANY— the don’t-care variable (clingo’s_), for slots whose value is irrelevant. Variables.V— variables by attribute:V.CellisVariable("Cell"), no declaration needed. Variables.Vars— the class behindV: variables by attribute access, withV.C[1]for indexed names. Variables.Choice— the choice-rule builder: the solver’s decision space, withexactly()/at_least()/at_most()bounds. Choice rules.ConditionalLiteral—p(X) : q(X)for rule bodies andshow_when(). Conditional literals.RangePool— a contiguous range, rendering1..5. Pools and ranges.ExplicitPool— an explicit alternative set, rendering(1;3;5). Pools and ranges.SUP/INF— clingo’s#sup/#inf, the greatest and least elements of the term ordering. Constants and extremes.
Aggregates
All five are taught in Aggregates; put one in a comparison to make a guard — Guards done right.
Count—#count: how many distinct elements hold.Sum—#sum: the total of weighted elements.SumPlus—#sum+: the total counting positive weights only.Min—#min: the least weight among elements that hold.Max—#max: the greatest weight among elements that hold.
Rule-building utilities
pool()— build the right pool automatically from a Python range, list, or tuple. Pools and ranges.Not()— default negation as a function (the~operator’s spelling for expressions); on a plain comparison it builds the complement. Default negation.Compl()— bitwise complement, rendering clingo’s~(the Python~operator is reserved for negation). Doubled, it collapses and hands back the inner term. Operator table, doubled unary operators.
Hierarchy types
The weaker-guarantee block: annotate with these, rarely construct them. The library is built around a hierarchy of term types representing different ASP constructs:
- `Term` (abstract base class)
- `ComparableTerm` (abstract: usable in comparisons; provides `==`, `!=`, `<`, `<=`, `>`, `>=`)
- `Value` (abstract, for basic values — also a `BasicTerm`)
- `Variable` (e.g., `X`, `Y`)
- `ConstantBase` (abstract)
- `Number` (numeric constants, e.g., `42`)
- `String` (string literals, e.g., `"hello"`)
- `DefinedConstant` (#const-defined constants, e.g., `max_size`)
- `Supremum` / `Infimum` (`#sup`/`#inf`, the ordering's end markers; `SUP` and `INF` are the singletons)
- `Expression` (arithmetic expressions, e.g., `X+Y*2`)
- `AggregateBase` (abstract marker so core can recognize aggregates)
- `Aggregate` (abstract)
- `Count`, `Sum`, `SumPlus`, `Min`, `Max`
- `BasicTerm` (abstract, can be direct predicate arguments: `Value`, `Predicate`, `Pool`)
- `Predicate` (e.g., `person(john, 42)`)
- `Pool` (abstract)
- `RangePool` (e.g., `1..5`)
- `ExplicitPool` (e.g., `(1;3;5)`)
- `Negatable` (abstract mixin: `~` builds `not term` on atoms; on plain comparisons it builds the complement — see `Not`)
- `Comparison` (comparisons, e.g., `X < Y`)
- `DefaultNegation` (default negation, e.g., `not p(X)`)
- `ConditionalLiteral` (e.g., `p(X) : q(X)`)
- `Choice` (e.g., `{ p(X) : q(X) }`)
One line per exported symbol, in __all__ order:
| Symbol | Annotate with it when |
|---|---|
ConditionType |
A parameter accepts a condition: a Predicate atom, a DefaultNegation, or a Comparison. |
ConditionedElement |
You hold one head-plus-conditions element of a choice or aggregate — what add() builds. |
TupleTermType |
A parameter accepts an aggregate element or optimization term: int, str, Value, Expression, or Predicate. |
CardinalityType |
A parameter accepts a choice bound (exactly()/at_least()/at_most()): int, Value, or Expression. |
PredicateTypes |
You pass the (name, arity) → predicate-class mapping that convert_symbol_to_predicate decodes with. |
FieldAsTermType |
A parameter accepts what a predicate field holds: Value, Predicate, Expression, or Pool. |
PredicateOccurrence |
You consume occurrence collection: a (class, negated, is_atom) triple. |
Term |
You accept any term at all — the hierarchy’s abstract root. |
BasicTerm |
You accept anything usable directly as a predicate argument. |
Value |
You accept a basic value (a variable or constant); equal live values are the same object — see Atoms as values. |
ConstantBase |
You accept any constant but not a variable. |
ComparableTerm |
You accept anything that may appear in a comparison. |
Negatable |
You accept anything ~ applies to. |
ProgramElement |
You hold one rendered statement of a program — a rule, comment, or blank line (see RenderedLine). |
Expression |
You hold arithmetic built from operators on values, like X + Y * 2 — see Arithmetic. |
Comparison |
You hold what a comparison operator on terms builds — see Comparisons. |
ComparisonOperator |
You name one of the six comparison operators. |
Operation |
You name an arithmetic or bitwise operation. |
RenderingContext |
You call a term’s render() yourself and must say where its output lands. |
DefaultNegation |
You hold a not p(X) literal, built by Not()/~ — see Default negation. |
DefinedConstant |
You hold what define_constant() returns — see Constants and extremes. |
Aggregate |
You accept any of the five aggregates. |
Pool |
You accept either pool kind — see Pools and ranges. |
Number |
You hold an integer constant term (plain ints auto-coerce on write). |
String |
You hold a quoted-string constant term (plain strs auto-coerce on write). |
Supremum / Infimum |
You annotate the types of the SUP and INF singletons. |
Interop with raw clingo symbols
Both are taught in Clingo symbol interop.
convert_predicate_to_symbol()— a typed atom → aclingo.Symbol, recursively, sign included, for driving the clingo API directly.convert_symbol_to_predicate()— aclingo.Symbol→ a typed atom, given aPredicateTypesmapping to decode with.
Metadata
__version__— the installed package version string (pyproject.tomlis the source of truth;version.pyreads the installed metadata at runtime).