Using MeTTa from Python
← MeTTa Tutorial · Lesson 5 of 5
Using MeTTa from Python. MeTTa ships as a Python library (the hyperon package), so you can run MeTTa programs from Python, read their results, and extend MeTTa with your own Python functions and objects.
Running MeTTa in Python
Create an interpreter, then run a program. Each !-line returns its results, and run collects them as a list of lists (one inner list per evaluated expression):
from hyperon import MeTTa
metta = MeTTa()
result = metta.run('''
(= (square $x) (* $x $x))
! (square 8)
''')
print(result) # 64
Parsing grounded atoms
Python values cross into MeTTa as grounded atoms. Build one with ValueAtom and register it; construct symbols and expressions with S and E:
from hyperon import MeTTa, ValueAtom, S, E
metta = MeTTa()
metta.register_atom('&pi', ValueAtom(3.14159)) # a grounded value
print(metta.run('! &pi')) # 3.14159
expr = E(S('parent'), S('Tom'), S('Bob')) # builds (parent Tom Bob)
Embedding Python objects
Wrap a Python function as a grounded operation with OperationAtom and register it — MeTTa can then call it like any built-in. (The & prefix is the naming convention for grounded atoms.)
from hyperon import MeTTa, OperationAtom
def shout(text):
return text.upper() # plain Python; the result is auto-wrapped
metta = MeTTa()
metta.register_atom('&shout', OperationAtom('&shout', shout))
print(metta.run('! (&shout "hello")')) # HELLO
This two-way bridge — MeTTa orchestrating symbolic reasoning, Python supplying numeric, I/O, and neural building blocks — is how Hyperon integrates learning and reasoning components in practice.
Course complete
You’ve covered the MeTTa basics: evaluation, knowledge and queries, types, the standard library, and the Python bridge. From here, explore the MeTTa Deep Dive for the formal semantics and implementation stack, try the Hyperon Experimental reference runtime, or practise with the iCog MeTTa training challenges.