# How to call Python Methods from Mathematica employing ExternalEvaluate?

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"]];


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

from math import pi
class sphere(object):

def volume(self):



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

• What have you tried, and where did you get stuck? – MarcoB Mar 16 at 3:53
• 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. – Ben Izd Mar 16 at 5:02
• Is s equal to StartExternalSession["Python"] or is it something different? @BenyIzd – user10181864 Mar 16 at 5:40
• yes s is your pySession. @user10181864 – Ben Izd Mar 16 at 8:03
• It works. You should submit an answer @BenyIzd – user10181864 Mar 16 at 8:29

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 volume(self):



### Passing data

ExternalEvaluate[pySession,
");sp1.volume()"]

(*Out: 33.5103*)


Or you can make it more readable by using StringForm:

ExternalEvaluate[pySession,
ToString@StringForm["sp2=sphere();sp2.volume()",

DeleteObject[pySession]