Skip to content

Variable

relationalai.semantics.frontend.base

Represents a composable value in the semantics DSL.

A Variable is the base type for most objects you use when building queries and definitions. Variables are placeholders that can be combined into larger expressions via Python operators and then passed to fragment/model methods like Model.where and Model.select.

Common subclasses include Concept (entity types), Relationship, Ref (named entity references created by Concept.ref), Chain (property/relationship access like Person.age), and Expression (relationship calls and composed arithmetic/comparison expressions).

  • model

    (Model) - The semantic model this variable belongs to.

Build a filter with variable comparisons and select an aliased column:

>>> from relationalai.semantics import Integer, Model, String
>>> m = Model()
>>> Person = m.Concept("Person")
>>> m.define(
... Person.new(id=1, name="Alice", age=30),
... Person.new(id=2, name="Bob", age=17),
... )
>>> m.where(Person.age >= 18).select(Person.name.alias("NAME")).to_df()

Most users should not instantiate this class directly. You typically obtain variables by:

  • Creating concepts via Model.Concept.
  • Accessing relationships as attributes (e.g. Person.age).
  • Creating reference variables via Concept.ref.

Variables overload several Python operators to build DSL expressions:

  • Arithmetic operators like + and * return an Expression.
  • Comparison operators like == and >= return an expression suitable for use in where/require clauses.
  • Use & and | to combine conditions; do not use Python’s and/or.
  • For relationships/properties/chains (e.g. Person.age), operators apply to the output field (the last field). To work with a non-output field, index the relationship/property/chain to get a FieldRef, e.g. Person.jobs["start_date"].

Variable objects cannot be used in Python boolean contexts (if / while), and they cannot be iterated or passed to len(); these usages raise RAIException with a helpful message.

Variable.__add__(other)

Return an addition expression (self + other).

This enables Python’s + operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__radd__(other)

Return an addition expression (other + self).

This is the reflected form of Variable.__add__. It enables expressions like 1 + Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__mul__(other)

Return a multiplication expression (self * other).

This enables Python’s * operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable multiplication expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rmul__(other)

Return a multiplication expression (other * self).

This is the reflected form of Variable.__mul__. It enables expressions like 365 * Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

  • Expression - A composable multiplication expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__sub__(other)

Return a subtraction expression (self - other).

This enables Python’s - operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable subtraction expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rsub__(other)

Return a subtraction expression (other - self).

This is the reflected form of Variable.__sub__. It enables expressions like 5 - Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

  • Expression - A composable subtraction expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__truediv__(other)

Return a division expression (self / other).

This enables Python’s / operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rtruediv__(other)

Return a division expression (other / self).

This is the reflected form of Variable.__truediv__. It enables expressions like 1 / Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__floordiv__(other)

Return a floor division expression (self // other).

This enables Python’s // operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable floor division expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rfloordiv__(other)

Return a floor division expression (other // self).

This is the reflected form of Variable.__floordiv__. It enables expressions like 5 // Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

  • Expression - A composable floor division expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__pow__(other)

Return an exponentiation expression (self ** other).

This enables Python’s ** operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable exponentiation expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rpow__(other)

Return an exponentiation expression (other ** self).

This is the reflected form of Variable.__pow__. It enables expressions like 2 ** Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

  • Expression - A composable exponentiation expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__mod__(other)

Return a modulo expression (self % other).

This enables Python’s % operator for semantics DSL variables.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable modulo (remainder) expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__rmod__(other)

Return a modulo expression (other % self).

This is the reflected form of Variable.__mod__. It enables expressions like 10 % Person.age.

Parameters:

  • other

    (Value) - The left-hand operand.

Returns:

  • Expression - A composable modulo (remainder) expression.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__neg__()

Return a negation expression (-self).

This enables Python’s unary - operator for semantics DSL variables. The negation is represented as multiplication by -1 in the DSL.

Returns:

Variable.__gt__(other)

Return a greater-than filter expression (self > other).

This enables Python’s > operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__ge__(other)

Return a greater-than-or-equal filter expression (self >= other).

This enables Python’s >= operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__lt__(other)

Return a less-than filter expression (self < other).

This enables Python’s < operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__le__(other)

Return a less-than-or-equal filter expression (self <= other).

This enables Python’s <= operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__eq__(other) -> Any

Return an equality filter expression (self == other).

This enables Python’s == operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__ne__(other) -> Any

Return an inequality filter expression (self != other).

This enables Python’s != operator for semantics DSL variables. The returned expression is typically passed to Model.where or Fragment.where to filter a query.

Parameters:

  • other

    (Value) - The right-hand operand.

Returns:

  • Expression - A composable boolean expression suitable for where/require clauses.

Raises:

  • relationalai.util.error.RAIException - If other is an invalid value in an expression (for example, a table schema).
  • NotImplementedError - If a Python value cannot be converted to a supported literal.
Variable.__or__(other) -> Match

Return a match expression (self | other).

This enables Python’s | operator for semantics DSL values and statements.

a | b builds a Match with two branches. At execution time, the match picks the first branch (left-to-right) that can succeed for the current bindings.

This makes | the right tool for fallback/default behavior (“use this value if available, otherwise use that one”). If you instead want to combine the results from multiple branches (set-style union), use union or Model.union.

Parameters:

Returns:

  • Match - A composable match expression. You can extend it with additional branches via |.

Raises:

  • relationalai.util.error.RAIException - Raised in the following cases:
    • Branches return different numbers of values (for example, mixing a value-producing branch with a multi-column select).

Examples:

Set a default value for a property that may be missing:

>>> from relationalai.semantics import Model
>>> m = Model()
>>> User = m.Concept("User")
>>> m.define(
... User.new(username="alice", age=30, status="active"),
... User.new(username="bob", age=15, status="inactive"),
... User.new(username="carol", age=40),
... )
>>> # Get status with a default of "missing"
>>> status = User.status | "missing"
>>> m.select(User.username, status).to_df()

Notes:

Do not use Python’s boolean or with DSL variables. Use |, union, or Model.union instead.

Variable.__and__(other) -> Fragment

Return a fragment that combines conditions with AND (self & other).

Use & to explicitly conjoin conditions when building filters. This is equivalent to passing multiple conditions to Model.where. If other is a Fragment, this returns a new fragment with self added to other’s filters (roughly other.where(self)).

Parameters:

  • other

    (Statement or Fragment) - The right-hand operand. This is typically a condition expression, but it may also be an existing fragment to extend.

Returns:

  • Fragment - A composable fragment representing the conjunction.

Raises:

  • relationalai.util.error.RAIException - If other is not a valid statement in a filter.
  • NotImplementedError - If a Python value cannot be converted to a supported literal.

Examples:

Extend an existing fragment by adding another condition, then continue chaining:

>>> from relationalai.semantics import Model
>>> m = Model()
>>> User = m.Concept("User")
>>> m.define(
... User.new(username="alice", age=30, status="active"),
... User.new(username="bob", age=15, status="inactive"),
... User.new(username="carol", age=40),
... )
>>> active_users = m.where(User.status == "active")
>>> active_adults = active_users & (User.age >= 18)
>>> active_adults.select(User.username).to_df()

Notes:

Do not use Python’s boolean and with DSL variables. Use & (or pass multiple conditions to where) instead.

Variable.as_bool() -> AsBool

Return a boolean-typed wrapper around this variable.

as_bool() converts a DSL value/statement into a boolean expression that can be selected or composed like any other value. At execution time, the result is True when the wrapped expression can succeed for the current bindings, and False otherwise.

This is useful for turning presence into a column (for example, whether an optional property/relationship exists) and for explicitly selecting conditions as data.

Returns:

  • AsBool - A composable boolean expression.

Examples:

Select whether an optional property is present:

>>> from relationalai.semantics import Model
>>> m = Model()
>>> Person = m.Concept("Person")
>>> m.define(
... Person.new(name="Alice", nickname="Al", age=30),
... Person.new(name="Bob", age=17),
... )
>>> has_nickname = Person.nickname.as_bool()
>>> m.select(Person.name, has_nickname.alias("has_nickname")).to_df()

Select a condition as a column explicitly without using as_bool():

>>> is_adult = Person.age >= 18
>>> m.select(Person.name, is_adult.alias("is_adult")).to_df()

Notes:

  • You cannot use the result in Python boolean contexts (if / while); it is only meaningful inside semantics DSL expressions.
  • Comparisons and other filter-style expressions selected via Model.select are automatically treated as boolean outputs, so calling as_bool() is usually optional.
Variable.alias(alias: str) -> Alias

Return this value labeled with an output alias.

alias() wraps this value in an Alias. The alias is primarily used to name the output column when you pass the value to Model.select (and therefore affects column labels in Fragment.to_df).

When a selected value has an alias, the resulting fragment can also be indexed by that name (for example query["AGE"]).

Parameters:

  • alias

    (str) - The output name to attach to this value.

Returns:

  • Alias - A composable aliased value.

Examples:

Alias selected columns for readable output and later indexing:

>>> from relationalai.semantics import Model
>>> m = Model()
>>> Person = m.Concept("Person")
>>> m.define(
... Person.new(name="Alice", age=30),
... Person.new(name="Bob", age=17),
... )
>>> m.select(Person.name.alias("person_name"), Person.age.alias("person_age")).to_df()

Notes:

alias() does not rename the underlying concept/relationship; it only influences how the value is labeled in query outputs.

Variable.in_(values: Sequence[Value] | Variable)

Return an SQL IN-style filter expression.

Use in_ to test whether this value equals any of a set of candidate values.

This is a DSL-friendly alternative to Python’s in operator (which cannot be overloaded for DSL variables). The method lowers to an equality against a one-column value source:

  • If values is a Variable, this is equivalent to self == values.
  • If values is a sequence of Python primitives (str, int, float, bool), the method builds a one-column table via Model.data and compares against that column.
  • Otherwise, the method unions the provided items via Model.union and compares against the resulting value.

Parameters:

  • values

    (Sequence[Value] or Variable) - Candidate values to match.

Returns:

Raises:

  • relationalai.util.error.RAIException - Raised in the following cases:
    • Any provided value is not valid in an expression (for example, a table schema).
    • The constructed union branches return different numbers of values.
  • NotImplementedError - If a Python value cannot be converted to a supported literal.

Examples:

Filter rows by membership in a Python list:

>>> from relationalai.semantics import Model
>>> m = Model()
>>> Person = m.Concept("Person")
>>> m.define(
... Person.new(name="Alice", age=10),
... Person.new(name="Bob", age=30),
... Person.new(name="David", age=50),
... )
>>> m.where(Person.name.in_(["Alice", "Bob"])).select(Person.name, Person.age).to_df()

Pass a variable (for example the result of Model.union):

>>> allowed = m.union("Alice", "Bob")
>>> m.where(Person.name.in_(allowed)).select(Person.name).to_df()
VariableDSLBase
 semantics
├──  frontend
│   ├──  base
│   │   ├──  Aggregate
│   │   ├──  Alias
│   │   ├──  AsBool
│   │   ├──  Chain
│   │   ├──  Concept
│   │   ├──  Data
│   │   ├──  DerivedColumn
│   │   ├──  DerivedTable
│   │   ├──  Expression
│   │   ├──  FieldRef
│   │   ├──  FilterBy
│   │   ├──  Fragment
│   │   ├──  Literal
│   │   ├──  Match
│   │   ├──  New
│   │   ├──  NumberConcept
│   │   ├──  Property
│   │   ├──  Reading
│   │   ├──  Ref
│   │   ├──  Relationship
│   │   ├──  Table
│   │   └──  Union
│   └──  core
│       └──  AnyNumber
└──  std > re
    └──  RegexMatch
 semantics
├──  frontend > base
│   ├──  Alias
│   ├──  AsBool
│   ├──  Concept
│   │   └──  require
│   ├──  Variable
│   │   └──  in_
│   └──  Value
└──  std
    ├──  constraints
    │   └──  unique
    ├──  datetime
    │   ├──  date
    │   │   ├──  add
    │   │   └──  subtract
    │   └──  datetime
    │       ├──  add
    │       └──  subtract
    ├──  DateTimeValue
    ├──  DateValue
    ├──  FloatValue
    ├──  IntegerValue
    ├──  NumberValue
    └──  StringValue
 semantics > std
├──  datetime
│   ├──  date
│   │   └──  range
│   └──  datetime
│       └──  range
├──  decimals
│   └──  decimal
├──  integers
│   ├──  int128
│   └──  int64
├──  numbers
│   ├──  integer
│   └──  number
├──  re
│   ├──  RegexMatch
│   │   ├──  group
│   │   └──  group_by_name
│   └──  findall
└──  strings
    └──  split
RelationalAI Documentation
└──  Build With RelationalAI
    └──  Understand how PyRel works
        ├──  Build a semantic model
        │   └──  Derive facts with logic
        │       └──  Write conditional definitions with Model.where and Model.define
        └──  Use advanced reasoning > Rules-based reasoning
            └──  Work with numbers