1
$\begingroup$

This question is about the compatibility of methods written in Python and ExternalEvaluate from Mathematica.

ExternalEvaluate allows Python functions to be called from Mathematica. For example, the function "surfaceArea" from sphere.py:

from math import pi
def surfaceArea(r):
    return 4*pi*r**2

may be called from Mathematica in the following way

pySession = StartExternalSession["Python"];
ExternalEvaluate[pySession, File["sphere.py"]];
radius = 2.0;
ExternalEvaluate[pySession, "surfaceArea" -> {radius}]

Now, consider the sphere Python class (sphereClass.py)

from math import pi
class sphere(object):

    def __init__(self,radius):
        self.radius = radius

    def volume(self):
        return (4/3)*pi*self.radius**3

Aim: Evaluate volume from sphereClass.py at radius = 2.0 employing ExternalEvaluate.

$\endgroup$
5
  • $\begingroup$ What have you tried, and where did you get stuck? $\endgroup$
    – MarcoB
    Commented Mar 16, 2021 at 3:53
  • $\begingroup$ There are diffrent ways to pass Mathematica data to python, one of the easiest one is ExternalEvaluate[s, "sp = sphere(" <> ExportString[radius, "PythonExpression"] <> ");sp.volume()"], which outputs 33.5103. $\endgroup$
    – Ben Izd
    Commented Mar 16, 2021 at 5:02
  • $\begingroup$ Is s equal to StartExternalSession["Python"] or is it something different? @BenyIzd $\endgroup$ Commented Mar 16, 2021 at 5:40
  • $\begingroup$ yes s is your pySession. @user10181864 $\endgroup$
    – Ben Izd
    Commented Mar 16, 2021 at 8:03
  • $\begingroup$ It works. You should submit an answer @BenyIzd $\endgroup$ Commented Mar 16, 2021 at 8:29

1 Answer 1

2
$\begingroup$

There are many ways to send Mathematica data to python, here you'll see direct string manipulation:

Initial code

pySession = StartExternalSession["Python"];
ExternalEvaluate[pySession, "from math import pi
class sphere(object):

    def __init__(self,radius):
        self.radius = radius

    def volume(self):
        return (4/3)*pi*self.radius**3"];

radius = 2.0;

Passing data

ExternalEvaluate[pySession, 
 "sp1=sphere(" <> ExportString[radius, "PythonExpression"] <> 
  ");sp1.volume()"]

(*Out: 33.5103*)

Or you can make it more readable by using StringForm:

ExternalEvaluate[pySession, 
 ToString@StringForm["sp2=sphere(``);sp2.volume()", 
   ExportString[radius, "PythonExpression"]]]

(*Out: 33.5103*)

finaly

Stop the session:

DeleteObject[pySession]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.