Skip to content

atoms

The Python wrapper for Hyperon Atom Rust types

Atom

Atom(catom)

Represents an Atom of any type

Source code in python/hyperon/atoms.py
def __init__(self, catom):
    """Initialize an Atom"""
    self.catom = catom

__del__

__del__()

Frees an Atom and all associated resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees an Atom and all associated resources."""
    hp.atom_free(self.catom)

__eq__

__eq__(other)

Checks if two atom objects represent the same conceptual Atom.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two atom objects represent the same conceptual Atom."""
    return (isinstance(other, Atom) and
            hp.atom_eq(self.catom, other.catom))

__repr__

__repr__()

Renders a human-readable text description of the Atom.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a human-readable text description of the Atom."""
    return hp.atom_to_str(self.catom)

get_metatype

get_metatype()

Gets the metatype (kind) of the current Atom instance

Source code in python/hyperon/atoms.py
def get_metatype(self):
    """Gets the metatype (kind) of the current Atom instance"""
    return hp.atom_get_metatype(self.catom)

iterate

iterate()

Performs a depth-first exhaustive iteration of an Atom and all its children recursively.

Source code in python/hyperon/atoms.py
def iterate(self):
    """Performs a depth-first exhaustive iteration of an Atom and all its children recursively."""
    res = hp.atom_iterate(self.catom)
    result = []
    for r in res:
        result.append(Atom._from_catom(r))
    return result

match_atom

match_atom(b)

Matches one Atom with another, establishing bindings between them.

Source code in python/hyperon/atoms.py
def match_atom(self, b):
    """Matches one Atom with another, establishing bindings between them."""
    return BindingsSet(hp.atom_match_atom(self.catom, b.catom))

AtomType

Defines all Atom types

Bindings

Bindings(bindings: Union[CBindings, None] = None)

Interface for working with atom matching and variable-to-atom binding.

Source code in python/hyperon/atoms.py
def __init__(self, bindings: Union[hp.CBindings, None] = None):
    """Initializes with or without pre-existing bindings."""
    if bindings is None:
        self.cbindings = hp.bindings_new()
    else:
        self.cbindings = bindings

__deepcopy__

__deepcopy__(memodict={})

Makes a "deep copy" of the bindings.

Source code in python/hyperon/atoms.py
def __deepcopy__(self, memodict={}):
    """Makes a "deep copy" of the bindings."""
    return self.clone()

__del__

__del__()

Frees the binding resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees the binding resources."""
    if self.cbindings is not None:
        hp.bindings_free(self.cbindings)

__enter__

__enter__()

For context management.

Source code in python/hyperon/atoms.py
def __enter__(self):
    """For context management."""
    return self

__eq__

__eq__(other)

Checks if two bindings objects contain identical associations.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two bindings objects contain identical associations."""
    return (isinstance(other, Bindings) and
            hp.bindings_eq(self.cbindings, other.cbindings))

__exit__

__exit__(exc_type, exc_val, exc_tb)

Frees resources on exit.

Source code in python/hyperon/atoms.py
def __exit__(self, exc_type, exc_val, exc_tb):
    """Frees resources on exit."""
    if self.cbindings is not None:
        hp.bindings_free(self.cbindings)
        self.cbindings = None

__repr__

__repr__()

Renders a text description of the bindings

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a text description of the bindings"""
    return hp.bindings_to_str(self.cbindings)

add_var_binding

add_var_binding(var: VariableAtom, atom: Atom) -> bool

Adds a binding between a variable and an Atom.

Source code in python/hyperon/atoms.py
def add_var_binding(self, var: VariableAtom, atom: Atom) -> bool:
    """Adds a binding between a variable and an Atom."""
    return hp.bindings_add_var_binding(self.cbindings, var.catom, atom.catom)

clone

clone()

Makes a "deep copy" of the bindings

Source code in python/hyperon/atoms.py
def clone(self):
    """Makes a "deep copy" of the bindings"""
    return Bindings(hp.bindings_clone(self.cbindings))

is_empty

is_empty() -> bool

Checks if a bindings contains no associations.

Source code in python/hyperon/atoms.py
def is_empty(self) -> bool:
    """Checks if a bindings contains no associations."""
    return hp.bindings_is_empty(self.cbindings)

iterator

iterator()

Returns an iterator over the variable-atom pairs in the bindings

Source code in python/hyperon/atoms.py
def iterator(self):
    """Returns an iterator over the variable-atom pairs in the bindings"""
    res = hp.bindings_list(self.cbindings)
    result = [(Atom._from_catom(r[0]), Atom._from_catom(r[1])) for r in res]
    return iter(result)

merge

merge(other: Bindings) -> BindingsSet

Merges with another Bindings instance, into a Bindings Set.

Source code in python/hyperon/atoms.py
def merge(self, other: 'Bindings') -> 'BindingsSet':
    """Merges with another Bindings instance, into a Bindings Set."""
    return BindingsSet(hp.bindings_merge(self.cbindings, other.cbindings))

narrow_vars

narrow_vars(vars)

Keeps only specific variable associations.

Source code in python/hyperon/atoms.py
def narrow_vars(self, vars ):
    """Keeps only specific variable associations."""
    cvars = hp.CVecAtom = hp.atom_vec_new()
    for var in vars:
        hp.atom_vec_push(cvars, var.catom)
    hp.bindings_narrow_vars(self.cbindings, cvars)
    hp.atom_vec_free(cvars)

resolve

resolve(var: VariableAtom) -> Union[Atom, None]

Finds the atom for a given variable

Source code in python/hyperon/atoms.py
def resolve(self, var: VariableAtom) -> Union[Atom, None]:
    """Finds the atom for a given variable"""
    raw_atom = hp.bindings_resolve(self.cbindings, var.catom)
    return None if raw_atom is None else Atom._from_catom(raw_atom)

BindingsSet

BindingsSet(input: Union[CBindingsSet, Bindings, None] = None)

Represents a set of Bindings frames, potentially expressing all possible matches produced by a match operation.

Source code in python/hyperon/atoms.py
def __init__(self, input: Union[hp.CBindingsSet, Bindings, None] = None):
    """Initializes with optional input."""
    self.shadow_list = None # A lazily initialized list that shadows the BindingsSet values for indexed access
    if input is None:
        self.c_set = hp.bindings_set_single()
    elif isinstance(input, Bindings):
        self.c_set = hp.bindings_set_from_bindings(input.cbindings)
    else:
        self.c_set = input

__deepcopy__

__deepcopy__(memodict={})

Makes a "deep copy" of a BindingsSet

Source code in python/hyperon/atoms.py
def __deepcopy__(self, memodict={}):
    """Makes a "deep copy" of a BindingsSet"""
    return self.clone()

__del__

__del__()

Frees the BindingsSet

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees the BindingsSet"""
    if self.c_set is not None:
        hp.bindings_set_free(self.c_set)
        self.c_set = None

__enter__

__enter__()

For context management.

Source code in python/hyperon/atoms.py
def __enter__(self):
    """For context management."""
    return self

__eq__

__eq__(other)

Checks if other BindingsSet contains identical associations.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if other BindingsSet contains identical associations."""
    return (isinstance(other, BindingsSet) and
            hp.bindings_set_eq(self.c_set, other.c_set))

__exit__

__exit__(exc_type, exc_val, exc_tb)

Frees resources on exit.

Source code in python/hyperon/atoms.py
def __exit__(self, exc_type, exc_val, exc_tb):
    """Frees resources on exit."""
    if self.c_set is not None:
        hp.bindings_set_free(self.c_set)
        self.c_set = None

__getitem__

__getitem__(key)

Gets a Bindings frame by index

Source code in python/hyperon/atoms.py
def __getitem__(self, key):
    """Gets a Bindings frame by index"""
    if self.shadow_list is None:
        result = hp.bindings_set_unpack(self.c_set)
        self.shadow_list = [{k: Atom._from_catom(v) for k, v in bindings.items()} for bindings in result]
    return self.shadow_list[key]

__repr__

__repr__()

Renders a text description of a BindingsSet

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a text description of a BindingsSet"""
    return hp.bindings_set_to_str(self.c_set)

add_var_binding

add_var_binding(var: VariableAtom, value: Atom) -> bool

Adds a new variable to atom association to every Bindings frame in a BindingsSet.

Source code in python/hyperon/atoms.py
def add_var_binding(self, var: VariableAtom, value: Atom) -> bool:
    """Adds a new variable to atom association to every Bindings frame in a
    BindingsSet.
    """
    self.shadow_list = None
    return hp.bindings_set_add_var_binding(self.c_set, var.catom, value.catom)

add_var_equality

add_var_equality(a: Atom, b: Atom) -> bool

Asserts equality between two Variable atoms in a BindingsSet.

Source code in python/hyperon/atoms.py
def add_var_equality(self, a: Atom, b: Atom) -> bool:
    """Asserts equality between two Variable atoms in a BindingsSet."""
    self.shadow_list = None
    return hp.bindings_set_add_var_equality(self.c_set, a.catom, b.catom)

clone

clone()

Makes a "deep copy" of a BindingsSet

Source code in python/hyperon/atoms.py
def clone(self):
    """Makes a "deep copy" of a BindingsSet"""
    return BindingsSet(hp.bindings_set_clone(self.c_set))

empty

empty()

Creates a new BindingsSet without any Bindings frames. Conceptually, this means no valid matches exist.

Source code in python/hyperon/atoms.py
def empty():
    """Creates a new BindingsSet without any Bindings frames.
    Conceptually, this means no valid matches exist.
    """
    return BindingsSet(hp.bindings_set_empty())

is_empty

is_empty() -> bool

Checks if a BindingsSet contains no Bindings frames, and thus indicates no match.

Source code in python/hyperon/atoms.py
def is_empty(self) -> bool:
    """Checks if a BindingsSet contains no Bindings frames, and thus indicates
    no match."""
    return hp.bindings_set_is_empty(self.c_set)

is_single

is_single() -> bool

Checks if a Bindings set contains a frame with no associations, and thus allows variables to take any value.

Source code in python/hyperon/atoms.py
def is_single(self) -> bool:
    """Checks if a Bindings set contains a frame with no associations, and
    thus allows variables to take any value.
    """
    return hp.bindings_set_is_single(self.c_set)

iterator

iterator()

Returns an iterator over all Bindings frames

Source code in python/hyperon/atoms.py
def iterator(self):
    """Returns an iterator over all Bindings frames"""
    res = hp.bindings_set_list(self.c_set)
    result = [Bindings(r) for r in res]
    return iter(result)

merge_into

merge_into(input: Union[BindingsSet, Bindings])

Merges the contents of another BindingsSet or Bindings frame.

Source code in python/hyperon/atoms.py
def merge_into(self, input: Union['BindingsSet', Bindings]):
    """Merges the contents of another BindingsSet or Bindings frame."""
    self.shadow_list = None
    if isinstance(input, BindingsSet):
        hp.bindings_set_merge_into(self.c_set, input.c_set)
    else:
        new_set = BindingsSet(input)
        hp.bindings_set_merge_into(self.c_set, new_set.c_set)

push

push(bindings: Bindings)

Adds a Bindings frame to an existing BindingsSet

Parameters

bindings: The Bindings set to incorporate into set. Ownership of this argument is taken by this function.

Source code in python/hyperon/atoms.py
def push(self, bindings: Bindings):
    """Adds a Bindings frame to an existing BindingsSet

    Parameters
    ----------
    bindings:
        The Bindings set to incorporate into set. Ownership of this argument is
        taken by this function.
    """
    self.shadow_list = None
    hp.bindings_set_push(self.c_set, bindings.cbindings)

ExpressionAtom

ExpressionAtom(catom)

Bases: Atom

An ExpressionAtom combines different kinds of Atoms, including expressions.

Source code in python/hyperon/atoms.py
def __init__(self, catom):
    """Initialize an expression atom"""
    super().__init__(catom)

__del__

__del__()

Frees an Atom and all associated resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees an Atom and all associated resources."""
    hp.atom_free(self.catom)

__eq__

__eq__(other)

Checks if two atom objects represent the same conceptual Atom.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two atom objects represent the same conceptual Atom."""
    return (isinstance(other, Atom) and
            hp.atom_eq(self.catom, other.catom))

__repr__

__repr__()

Renders a human-readable text description of the Atom.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a human-readable text description of the Atom."""
    return hp.atom_to_str(self.catom)

get_children

get_children()

Returns all children Atoms of an expression

Source code in python/hyperon/atoms.py
def get_children(self):
    """Returns all children Atoms of an expression"""
    return [Atom._from_catom(catom) for catom in hp.atom_get_children(self.catom)]

get_metatype

get_metatype()

Gets the metatype (kind) of the current Atom instance

Source code in python/hyperon/atoms.py
def get_metatype(self):
    """Gets the metatype (kind) of the current Atom instance"""
    return hp.atom_get_metatype(self.catom)

iterate

iterate()

Performs a depth-first exhaustive iteration of an Atom and all its children recursively.

Source code in python/hyperon/atoms.py
def iterate(self):
    """Performs a depth-first exhaustive iteration of an Atom and all its children recursively."""
    res = hp.atom_iterate(self.catom)
    result = []
    for r in res:
        result.append(Atom._from_catom(r))
    return result

match_atom

match_atom(b)

Matches one Atom with another, establishing bindings between them.

Source code in python/hyperon/atoms.py
def match_atom(self, b):
    """Matches one Atom with another, establishing bindings between them."""
    return BindingsSet(hp.atom_match_atom(self.catom, b.catom))

GroundedAtom

GroundedAtom(catom)

Bases: Atom

A GroundedAtom represents sub-symbolic knowledge. At the API level, it allows keeping data and behaviour inside an Atom. There are three aspects of a GroundedAtom which can be customized:

- the type of GroundedAtom is provided by the Atom itself;
- the matching algorithm used by the Atom;
- an Atom can be made executable, and used to apply sub-symbolic
  operations to other Atoms as arguments.
Source code in python/hyperon/atoms.py
def __init__(self, catom):
    """Initialize a GroundedAtom"""
    super().__init__(catom)

__del__

__del__()

Frees an Atom and all associated resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees an Atom and all associated resources."""
    hp.atom_free(self.catom)

__eq__

__eq__(other)

Checks if two atom objects represent the same conceptual Atom.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two atom objects represent the same conceptual Atom."""
    return (isinstance(other, Atom) and
            hp.atom_eq(self.catom, other.catom))

__repr__

__repr__()

Renders a human-readable text description of the Atom.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a human-readable text description of the Atom."""
    return hp.atom_to_str(self.catom)

get_grounded_type

get_grounded_type()

Retrieve the grounded type of the GroundedAtom.

Source code in python/hyperon/atoms.py
def get_grounded_type(self):
    """Retrieve the grounded type of the GroundedAtom."""
    return Atom._from_catom(hp.atom_get_grounded_type(self.catom))

get_metatype

get_metatype()

Gets the metatype (kind) of the current Atom instance

Source code in python/hyperon/atoms.py
def get_metatype(self):
    """Gets the metatype (kind) of the current Atom instance"""
    return hp.atom_get_metatype(self.catom)

get_object

get_object()

Returns the GroundedAtom object, or the Space wrapped inside a GroundedAtom, or convert supported Rust grounded objects into corresponding ValueObjects. Function raises TypeError when grounded atom cannot be converted to Python object. Uncatched Python exception can lead to Rust panic in some contexts, for example when exception is thrown from atomspace query unification procedure. It is highly recommended to call get_object method inside try-except block to catch TypeError.

Source code in python/hyperon/atoms.py
def get_object(self):
    """Returns the GroundedAtom object, or the Space wrapped inside a GroundedAtom,
       or convert supported Rust grounded objects into corresponding ValueObjects.
       Function raises TypeError when grounded atom cannot be converted to Python object. Uncatched
       Python exception can lead to Rust panic in some contexts, for example when exception is thrown
       from atomspace query unification procedure. It is highly recommended to call get_object method
       inside try-except block to catch TypeError.
    """
    # TODO: Here code assumes CGrounded object is always Python object.
    # This is not true in general case. To make code universal we need to
    # keep kind of the original runtime in CGrounded structure.
    if hp.atom_is_cgrounded(self.catom):
        return hp.atom_get_object(self.catom)
    else:
        return _priv_gnd_get_object(self)

iterate

iterate()

Performs a depth-first exhaustive iteration of an Atom and all its children recursively.

Source code in python/hyperon/atoms.py
def iterate(self):
    """Performs a depth-first exhaustive iteration of an Atom and all its children recursively."""
    res = hp.atom_iterate(self.catom)
    result = []
    for r in res:
        result.append(Atom._from_catom(r))
    return result

match_atom

match_atom(b)

Matches one Atom with another, establishing bindings between them.

Source code in python/hyperon/atoms.py
def match_atom(self, b):
    """Matches one Atom with another, establishing bindings between them."""
    return BindingsSet(hp.atom_match_atom(self.catom, b.catom))

GroundedObject

GroundedObject(content, id=None)

A GroundedObject holds some content and, optionally, an identifier.

Source code in python/hyperon/atoms.py
def __init__(self, content, id=None):
    """Initializes a new GroundedObject with the given content and identifier."""
    self.content = content
    self.id = id

__repr__

__repr__()

Returns the object's ID if present, or a string representation of its content if not.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Returns the object's ID if present, or a string representation of
    its content if not."""
    # Overwrite Python default representation of a string to use
    # double quotes instead of single quotes.
    if isinstance(self.content, str):
        newstr = repr(self.content)[1:-1].translate(str.maketrans({'"' : r'\"'}))
        return f'"{newstr}"'

    # Use default representation for everything else
    return repr(self.content) if self.id is None else self.id

copy

copy()

Returns a copy of this GroundedObject instance.

Note: Currently, this method returns the original instance.

Source code in python/hyperon/atoms.py
def copy(self):
    """
    Returns a copy of this GroundedObject instance.

    Note: Currently, this method returns the original instance.
    """
    return self

IncorrectArgumentError

Bases: Exception

Argument is not recognized by function implementation. It can be argument of incorrect type or in incorrect format. Interpreter handles this error similarly to the situation when pure function definition is not matched.

MatchableObject

MatchableObject(content, id=None)

Bases: ValueObject

Represents an object that can be involved in a matching operation with an Atom.

This class is meant to be subclassed by objects that define specific matching behavior with an Atom. It provides a stub method for the matching operation that raises a RuntimeError when called, which must be overridden by subclasses.

Inherits

ValueObject: The parent class that provides basic value-based equality and representation.

Methods:

  • match_

    A stub method for matching the object with an Atom.

Example

class MyMatchableObject(MatchableObject): def match_(self, atom): # Implement the matching logic here pass

my_obj = MyMatchableObject("some_value") my_obj.match_(some_atom) # Should not raise RuntimeError

Raises:

  • RuntimeError

    Raised when the match_ method is called without being overridden by a subclass.

Source code in python/hyperon/atoms.py
def __init__(self, content, id=None):
    """Initializes a new GroundedObject with the given content and identifier."""
    self.content = content
    self.id = id

value property

value

Gets the value of the object, which is its content.

__eq__

__eq__(other)

Compares the equality of this ValueObject with another based on their content.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Compares the equality of this ValueObject with another based on their content."""
    # TODO: We need to hook this up the the Value-Bridging mechanism when it's designed and built
    # https://github.com/trueagi-io/hyperon-experimental/issues/351

    # TODO: ?typecheck for the contents
    return isinstance(other, ValueObject) and self.content == other.content

__repr__

__repr__()

Returns the object's ID if present, or a string representation of its content if not.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Returns the object's ID if present, or a string representation of
    its content if not."""
    # Overwrite Python default representation of a string to use
    # double quotes instead of single quotes.
    if isinstance(self.content, str):
        newstr = repr(self.content)[1:-1].translate(str.maketrans({'"' : r'\"'}))
        return f'"{newstr}"'

    # Use default representation for everything else
    return repr(self.content) if self.id is None else self.id

copy

copy()

Returns a copy of this GroundedObject instance.

Note: Currently, this method returns the original instance.

Source code in python/hyperon/atoms.py
def copy(self):
    """
    Returns a copy of this GroundedObject instance.

    Note: Currently, this method returns the original instance.
    """
    return self

match_

match_(atom)

A stub method for matching the object with an Atom.

This method is intended to be overridden by subclasses to provide specific matching behavior with an Atom.

Parameters:

  • atom (Atom) –

    An Atom object to match against.

Raises:

  • RuntimeError

    Raised when this method is called without being overridden in a subclass.

Source code in python/hyperon/atoms.py
def match_(self, atom):
    """
    A stub method for matching the object with an Atom.

    This method is intended to be overridden by subclasses to provide specific
    matching behavior with an Atom.

    Parameters:
        atom (Atom): An Atom object to match against.

    Raises:
        RuntimeError: Raised when this method is called without being overridden in a subclass.
    """
    raise RuntimeError("MatchableObject::match_() is not implemented")

serialize

serialize(serializer)

Serialize standard Python values. This implementation is used to pass Python values into the foreign runtime.

Source code in python/hyperon/atoms.py
def serialize(self, serializer):
    """
    Serialize standard Python values. This implementation is used to
    pass Python values into the foreign runtime.
    """
    if isinstance(self.content, bool):
        return serializer.serialize_bool(self.content)
    elif isinstance(self.content, int):
        return serializer.serialize_int(self.content)
    elif isinstance(self.content, float):
        return serializer.serialize_float(self.content)
    elif isinstance(self.content, str):
        return serializer.serialize_str(self.content)
    else:
        return SerialResult.NOT_SUPPORTED

MettaError

Bases: Exception

Custom exception; raised when a error should be returned from OperationAtom, , but we don't want to output Python error stack.

NoReduceError

Bases: Exception

Custom exception; raised when a reduction operation cannot be performed.

OperationObject

OperationObject(name, op, unwrap=True)

Bases: GroundedObject

An OperationObject represents an operation as a grounded object, allowing for more advanced logic like lazy evaluation, type-checking, and more.

Inherits

GroundedObject: The parent class that provides the basic wrapper around content.

Attributes:

  • unwrap (bool) –

    Determines whether to unwrap the content of GroundedAtoms when passed as arguments to the operation.

Properties

op: Returns the operation function. name: Returns the identifier name for this operation object.

Methods:

  • execute

    Executes the operation with the provided arguments.

  • __eq__

    Compares the equality of this OperationObject instance with another.

Example

def add(a, b): return a + b

op_obj = OperationObject("addition", add) result = op_obj.execute(3, 4)

Parameters: name (str): The identifier for this operation. op (function): The function representing the operation. unwrap (bool, optional): Whether to unwrap GroundedAtom content when applying the operation. Defaults to True.

Source code in python/hyperon/atoms.py
def __init__(self, name, op, unwrap=True):
    """
    Initializes a new OperationObject with a name identifier, operation function,
    and an optional unwrap flag.
    Parameters:
        name (str): The identifier for this operation.
        op (function): The function representing the operation.
        unwrap (bool, optional): Whether to unwrap GroundedAtom content when applying
                                 the operation. Defaults to True.

    """
    super().__init__(op, name)
    self.unwrap = unwrap

name property

name

Returns the identifier name for this operation object.

op property

op

Returns the operation function.

__eq__

__eq__(other)

Compares the equality of this OperationObject with another based on their names.

Parameters:

Returns:

  • True if both OperationObjects have the same name; False otherwise.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """
    Compares the equality of this OperationObject with another based on their names.

    Parameters:
        other (OperationObject): Another OperationObject instance to compare.

    Returns:
        True if both OperationObjects have the same name; False otherwise.
    """
    return isinstance(other, OperationObject) and self.name == other.name

__repr__

__repr__()

Returns the object's ID if present, or a string representation of its content if not.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Returns the object's ID if present, or a string representation of
    its content if not."""
    # Overwrite Python default representation of a string to use
    # double quotes instead of single quotes.
    if isinstance(self.content, str):
        newstr = repr(self.content)[1:-1].translate(str.maketrans({'"' : r'\"'}))
        return f'"{newstr}"'

    # Use default representation for everything else
    return repr(self.content) if self.id is None else self.id

copy

copy()

Returns a copy of this GroundedObject instance.

Note: Currently, this method returns the original instance.

Source code in python/hyperon/atoms.py
def copy(self):
    """
    Returns a copy of this GroundedObject instance.

    Note: Currently, this method returns the original instance.
    """
    return self

execute

execute(*atoms, res_typ=AtomType.UNDEFINED)

Executes the operation with the provided arguments.

Parameters:

  • *args

    Arguments to pass to the operation function.

  • res_typ (AtomType, default: UNDEFINED ) –

    The expected result type. Defaults to AtomType.UNDEFINED.

Returns:

  • The result of the operation.

Raises:

  • NoReduceError

    Raised when unwrap=True and a non-GroundedAtom argument is provided.

  • RuntimeError

    Raised when the result of the operation is not a list.

Note

Depending on the unwrap attribute, this method will either unwrap GroundedAtoms before passing them to the operation or pass them as is.

Source code in python/hyperon/atoms.py
def execute(self, *atoms, res_typ=AtomType.UNDEFINED):
    """
    Executes the operation with the provided arguments.

    Parameters:
        *args: Arguments to pass to the operation function.
        res_typ (AtomType, optional): The expected result type. Defaults to AtomType.UNDEFINED.

    Returns:
        The result of the operation.

    Raises:
        NoReduceError: Raised when `unwrap=True` and a non-GroundedAtom argument is provided.
        RuntimeError: Raised when the result of the operation is not a list.

    Note:
        Depending on the `unwrap` attribute, this method will either unwrap GroundedAtoms
        before passing them to the operation or pass them as is.
    """
    # type-check?
    if self.unwrap:
        args, kwargs = unwrap_args(atoms)
        try:
            result = self.op(*args, **kwargs)
        except MettaError as e:
            return [E(S('Error'), *e.args)]
        if result is None:
            return [Atoms.UNIT]
        if callable(result):
            return [OperationAtom(repr(result), result, unwrap=True)]
        return [ValueAtom(result, res_typ)]
    else:
        result = self.op(*atoms)
        try:
            iter(result)
        except TypeError:
            raise RuntimeError("Grounded operation `" + self.name + "` should return list")
        return result

SymbolAtom

SymbolAtom(catom)

Bases: Atom

A SymbolAtom represents a single concept, identified by name. If two symbols have the same name, they reference the same concept.

Source code in python/hyperon/atoms.py
def __init__(self, catom):
    """Initialize a SymbolAtom"""
    super().__init__(catom)

__del__

__del__()

Frees an Atom and all associated resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees an Atom and all associated resources."""
    hp.atom_free(self.catom)

__eq__

__eq__(other)

Checks if two atom objects represent the same conceptual Atom.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two atom objects represent the same conceptual Atom."""
    return (isinstance(other, Atom) and
            hp.atom_eq(self.catom, other.catom))

__repr__

__repr__()

Renders a human-readable text description of the Atom.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a human-readable text description of the Atom."""
    return hp.atom_to_str(self.catom)

get_metatype

get_metatype()

Gets the metatype (kind) of the current Atom instance

Source code in python/hyperon/atoms.py
def get_metatype(self):
    """Gets the metatype (kind) of the current Atom instance"""
    return hp.atom_get_metatype(self.catom)

get_name

get_name()

Returns the name of the Atom.

Source code in python/hyperon/atoms.py
def get_name(self):
    """Returns the name of the Atom."""
    return hp.atom_get_name(self.catom)

iterate

iterate()

Performs a depth-first exhaustive iteration of an Atom and all its children recursively.

Source code in python/hyperon/atoms.py
def iterate(self):
    """Performs a depth-first exhaustive iteration of an Atom and all its children recursively."""
    res = hp.atom_iterate(self.catom)
    result = []
    for r in res:
        result.append(Atom._from_catom(r))
    return result

match_atom

match_atom(b)

Matches one Atom with another, establishing bindings between them.

Source code in python/hyperon/atoms.py
def match_atom(self, b):
    """Matches one Atom with another, establishing bindings between them."""
    return BindingsSet(hp.atom_match_atom(self.catom, b.catom))

ValueObject

ValueObject(content, id=None)

Bases: GroundedObject

A ValueObject is a specialized form of GroundedObject, which treats its content as a value. It allows for equality comparison between the content of two ValueObjects.

Example

obj1 = ValueObject(5) obj2 = ValueObject(5) obj3 = ValueObject(6)

print(obj1 == obj2) # True print(obj1 == obj3) # False

Source code in python/hyperon/atoms.py
def __init__(self, content, id=None):
    """Initializes a new GroundedObject with the given content and identifier."""
    self.content = content
    self.id = id

value property

value

Gets the value of the object, which is its content.

__eq__

__eq__(other)

Compares the equality of this ValueObject with another based on their content.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Compares the equality of this ValueObject with another based on their content."""
    # TODO: We need to hook this up the the Value-Bridging mechanism when it's designed and built
    # https://github.com/trueagi-io/hyperon-experimental/issues/351

    # TODO: ?typecheck for the contents
    return isinstance(other, ValueObject) and self.content == other.content

__repr__

__repr__()

Returns the object's ID if present, or a string representation of its content if not.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Returns the object's ID if present, or a string representation of
    its content if not."""
    # Overwrite Python default representation of a string to use
    # double quotes instead of single quotes.
    if isinstance(self.content, str):
        newstr = repr(self.content)[1:-1].translate(str.maketrans({'"' : r'\"'}))
        return f'"{newstr}"'

    # Use default representation for everything else
    return repr(self.content) if self.id is None else self.id

copy

copy()

Returns a copy of this GroundedObject instance.

Note: Currently, this method returns the original instance.

Source code in python/hyperon/atoms.py
def copy(self):
    """
    Returns a copy of this GroundedObject instance.

    Note: Currently, this method returns the original instance.
    """
    return self

serialize

serialize(serializer)

Serialize standard Python values. This implementation is used to pass Python values into the foreign runtime.

Source code in python/hyperon/atoms.py
def serialize(self, serializer):
    """
    Serialize standard Python values. This implementation is used to
    pass Python values into the foreign runtime.
    """
    if isinstance(self.content, bool):
        return serializer.serialize_bool(self.content)
    elif isinstance(self.content, int):
        return serializer.serialize_int(self.content)
    elif isinstance(self.content, float):
        return serializer.serialize_float(self.content)
    elif isinstance(self.content, str):
        return serializer.serialize_str(self.content)
    else:
        return SerialResult.NOT_SUPPORTED

VariableAtom

VariableAtom(catom)

Bases: Atom

A VariableAtom represents a variable in an expression. It serves as a placeholder that can be matched with, or bound to other Atoms.

Source code in python/hyperon/atoms.py
def __init__(self, catom):
    """Initialize a VariableAtom"""
    super().__init__(catom)

__del__

__del__()

Frees an Atom and all associated resources.

Source code in python/hyperon/atoms.py
def __del__(self):
    """Frees an Atom and all associated resources."""
    hp.atom_free(self.catom)

__eq__

__eq__(other)

Checks if two atom objects represent the same conceptual Atom.

Source code in python/hyperon/atoms.py
def __eq__(self, other):
    """Checks if two atom objects represent the same conceptual Atom."""
    return (isinstance(other, Atom) and
            hp.atom_eq(self.catom, other.catom))

__repr__

__repr__()

Renders a human-readable text description of the Atom.

Source code in python/hyperon/atoms.py
def __repr__(self):
    """Renders a human-readable text description of the Atom."""
    return hp.atom_to_str(self.catom)

get_metatype

get_metatype()

Gets the metatype (kind) of the current Atom instance

Source code in python/hyperon/atoms.py
def get_metatype(self):
    """Gets the metatype (kind) of the current Atom instance"""
    return hp.atom_get_metatype(self.catom)

get_name

get_name()

Returns the name of the Atom.

Source code in python/hyperon/atoms.py
def get_name(self):
    """Returns the name of the Atom."""
    return hp.atom_get_name(self.catom)

iterate

iterate()

Performs a depth-first exhaustive iteration of an Atom and all its children recursively.

Source code in python/hyperon/atoms.py
def iterate(self):
    """Performs a depth-first exhaustive iteration of an Atom and all its children recursively."""
    res = hp.atom_iterate(self.catom)
    result = []
    for r in res:
        result.append(Atom._from_catom(r))
    return result

match_atom

match_atom(b)

Matches one Atom with another, establishing bindings between them.

Source code in python/hyperon/atoms.py
def match_atom(self, b):
    """Matches one Atom with another, establishing bindings between them."""
    return BindingsSet(hp.atom_match_atom(self.catom, b.catom))

parse_name staticmethod

parse_name(name)

Construct new VariableAtom instance from VariableAtom.get_name() method results.

Source code in python/hyperon/atoms.py
@staticmethod
def parse_name(name):
    """Construct new VariableAtom instance from VariableAtom.get_name()
    method results."""
    return VariableAtom(hp.atom_var_parse_name(name))

E

E(*args)

A convenient method to construct an ExpressionAtom

Source code in python/hyperon/atoms.py
def E(*args):
    """A convenient method to construct an ExpressionAtom"""
    return ExpressionAtom(hp.atom_expr([atom.catom for atom in args]))

G

G(object, type=AtomType.UNDEFINED)

A convenient method to construct a GroundedAtom

Source code in python/hyperon/atoms.py
def G(object, type=AtomType.UNDEFINED):
    """A convenient method to construct a GroundedAtom"""
    return GroundedAtom(_priv_atom_gnd(object, type))

MatchableAtom

MatchableAtom(value, type_name=None, atom_id=None)

Creates a Grounded Atom that wraps a matchable value, optionally specifying its type and identifier.

Source code in python/hyperon/atoms.py
def MatchableAtom(value, type_name=None, atom_id=None):
    """
    Creates a Grounded Atom that wraps a matchable value, optionally specifying its type and identifier.
    """
    return G(MatchableObject(value, atom_id), _type_sugar(type_name))

OperationAtom

OperationAtom(name, op, type_names=None, unwrap=True)

An OperationAtom wraps an operation with optional type information into a GroundedAtom and associates a name with it. Useful for registering custom operations that can be executed in an Atom-based computational environment.

Source code in python/hyperon/atoms.py
def OperationAtom(name, op, type_names=None, unwrap=True):
    """
    An OperationAtom wraps an operation with optional type information into a GroundedAtom
    and associates a name with it. Useful for registering custom operations
    that can be executed in an Atom-based computational environment.
    """
    return G(OperationObject(name, op, unwrap), _type_sugar(type_names))

PrimitiveAtom

PrimitiveAtom(value, type_name=None, atom_id=None)

Creates a GroundedAtom that wraps a given Python primitive value without converting it into the MeTTa primitive. By default ValueAtom function converts Python primitives into MeTTa ones. This function is added to override this rule if needed.

Source code in python/hyperon/atoms.py
def PrimitiveAtom(value, type_name=None, atom_id=None):
    """
    Creates a GroundedAtom that wraps a given Python primitive value without
    converting it into the MeTTa primitive. By default ValueAtom function
    converts Python primitives into MeTTa ones. This function is added to
    override this rule if needed.
    """
    PRIMITIVE_TYPES = (int, float, bool)
    assert isinstance(value, PRIMITIVE_TYPES), f"Primitive value {PRIMITIVE_TYPES} is expected"
    type = _type_sugar(type_name)
    return GroundedAtom(hp.atom_py(ValueObject(value, atom_id), type.catom))

S

S(name)

A convenient method to construct a SymbolAtom

Source code in python/hyperon/atoms.py
def S(name):
    """A convenient method to construct a SymbolAtom"""
    return SymbolAtom(hp.atom_sym(name))

V

V(name)

A convenient method to construct a VariableAtom

Source code in python/hyperon/atoms.py
def V(name):
    """A convenient method to construct a VariableAtom"""
    return VariableAtom(hp.atom_var(name))

ValueAtom

ValueAtom(value, type_name=None, atom_id=None)

Creates a GroundedAtom that wraps a given value, optionally specifying its type and identifier. It has special processing for the objects which have cspace attribute and for ValueObject instances of primitive types. Spaces usually should be treated by a special way. Primitive atoms are converted into the MeTTa primitives.

Source code in python/hyperon/atoms.py
def ValueAtom(value, type_name=None, atom_id=None):
    """
    Creates a GroundedAtom that wraps a given value, optionally specifying its
    type and identifier. It has special processing for the objects which have
    cspace attribute and for ValueObject instances of primitive types. Spaces
    usually should be treated by a special way. Primitive atoms are converted
    into the MeTTa primitives.
    """
    return G(ValueObject(value, atom_id), _type_sugar(type_name))

atoms_are_equivalent

atoms_are_equivalent(first, second)

Check if two atoms are equivalent

Source code in python/hyperon/atoms.py
def atoms_are_equivalent(first, second):
    """Check if two atoms are equivalent"""
    return hp.atoms_are_equivalent(first.catom, second.catom)