Question: best way to use mathics as a module in Python

30 views
Skip to first unread message

Brian Beckman

unread,
Nov 2, 2020, 2:02:06 PM11/2/20
to mathics-users
Hello, team:
(I am the same person who contributed the symbolic-logic tests from Gries & Schneider)

My use case is to run a mathics session inside another Python program. I want to do something like this:

import matics.session as ms

msession = ms.Session()

msession.evaluate_for_side_effect('x = {42, 43, 44}')  # <~~~ mathics code in string! return None or raise exception; anything reasonable

msession.evalutae_for_result('x')  # <~~~ want this to return string '{42, 43, 44}'

messsion.evaluate_for_output('Print[x[[1]]];')  # <~~~ want this to return string '42'

I'm more than happy to reuse the existing parser-feeder infrastructure as illustrated in mathics.main, mathics.benchmark, mathics.test, etc., but I've encountered a few roadblocks like no $Line for the parser.

I'd be grateful for any guidance. Perhaps you have this already and I just haven't seen it. Perhaps there is an easy-ish way to adapt one of the existing "main" routines?

Mauricio Matera

unread,
Nov 3, 2020, 10:04:38 AM11/3/20
to mathics-users
To have a session object seems to be a good idea. By now, the way to run WL code from Python  would be something like the following minimal example:

`
from mathics.core.parser import parse, SingleLineFeeder
from mathics.core.definitions import Definitions
from mathics.core.evaluation import Evaluation

definitions = Definitions(add_builtin=True)  # Holds definitions for the session.
evaluation = Evaluation(definitions=definitions, catch_interrupt=False)  # The evaluation object

def evaluate(str_expression):
    expr = parse(definitions, SingleLineFeeder(str_expression))
    return expr.evaluate(evaluation)


evaluate('x= {42, 43, 44}')  # Evaluate without keeping the output
res = evaluate('x[[2]]^2')     # Evaluate and store the output
print(res.to_sympy())         # Translate to sympy and print it.

`

Brian Beckman

unread,
Nov 3, 2020, 6:26:52 PM11/3/20
to mathics-users
That's fantastic! Exactly what I needed to unblock! Thank you very much
Reply all
Reply to author
Forward
0 new messages