API Reference
Every public name, grouped by task in __all__’s own order: one line on
when you reach for it, and a link to the guide section that teaches it.
What to read first, though, is what you may rely on.
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, and the program can assign each one a segment group at attach sorender(group=...)emits it into a standalone file. 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— the typed field annotation:Field[int],Field[str],Field[SomePredicate],Field[PredicateArg]. A descriptor with two types on purpose — built from the ground type or any rule term, read back as the ground type — which is why it, and not a barestr, must be what the annotation says: a type checker types the constructor from it. Declaring predicates.field— the defaulted-field specifier:note: Field[str] = field(default="hi")declares a field that fills in when omitted. The one spelling of a default the runtime and the type checkers agree on (the checker learns the field is optional and checks the default against the annotation; a plain= "hi"is refused at class creation); the default may be any value the field accepts on write, rule terms included. Validated when the class is defined. The fine print.PredicateArg— the “any predicate argument” union; annotating a field withField[PredicateArg]makes the slot polymorphic. 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, guarded with comparison operators (menu >= 2,2 <= menu <= 4). 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`)
- `AggregateComparison` (a side holds an aggregate, e.g., `#count{ X : p(X) } >= 3`; construction returns it automatically)
- `AggregateBand` (a chained comparison's band, e.g., `3 <= #count{ X : p(X) } < 7`)
- `DefaultNegation` (default negation, e.g., `not p(X)`)
- `NegatedAtom` (`not p(1)` exactly — an `AtomLiteral`; construction returns it automatically)
- `ConditionalLiteral` (e.g., `p(X) : q(X)`)
- `ChoiceBand` (a guarded choice head, e.g., `2 { p(X) : q(X) } 4` — not a
`Comparison`: it shares the operator spelling and the `ChainLink`
contract, nothing literal)
- `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 cardinality guard (the count in menu >= count): 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: atoms, comparisons, negations. (A ChoiceBand is deliberately not here — a head has no negation.) |
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. |
AggregateComparison |
You hold a comparison one of whose sides is an aggregate (Count(...) >= 3) — never constructed by name — building any comparison with an aggregate operand returns one — so isinstance is the exact test for “aggregate-bearing”. |
AggregateBand |
You hold what a chained comparison over an aggregate builds (3 <= Count(...) < 7) — you never construct one, but a chain hands you one to isinstance — see Guards done right. |
ChoiceBand |
You hold a guarded choice head (menu >= 2, 2 <= menu <= 4) — the comparison operators on a Choice build one, sharing the choice they guard — see Choice rules. |
ChainLink |
You accept what the chain detector reads: a node storing its spelling as (left, operator, right) in rendered order — Comparison and ChoiceBand, the two classes chained comparisons build. |
ChoiceGuard |
You read a band’s guards: one (ComparisonOperator, term) pair in rendered order, from lower_guard/upper_guard. |
ChoiceHead |
A parameter accepts what choose() states: a Choice, guarded (ChoiceBand) or bare. |
Requirable |
You accept the terms that can be required to hold — a Comparison or an atom (what require() takes; the grammar of Negatable). |
CostBound |
A parameter accepts a cost bound: a bare int (single-tier programs) or {priority: value} — optimize(bound=) reads it as a hint, solve(cost_bound=) as the admission rule. |
NegatedAtom |
You hold not atom exactly (what ~atom and Not(atom) build) — never constructed by name — negating an atom returns one — the shape assumptions accept. |
AtomLiteral |
A parameter accepts or returns a literal formed from an atom — the atom itself, or its default negation (NegatedAtom). What assumptions= takes and unsat_core holds — see Ground once, solve many. |
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).