How to import Python Libraries with ExternalEvaluate?

I want to use specific python libraries via the Mathematica frontend. This is possible as follows

In[30]:= ExternalEvaluate["Python", "from sympy import isprime; isprime(7)"]
Out[30]= True

However, if I directly try to evaluate the same using > at the beginning of a line to use an external code cell, this does not work. For instance,

from sympy import isprime; isprime(7)

gives as output,

Out[31] = Failure[[WarningSign] Message: No module named 'sympy' Tag: PythonError ]

How can we make this work from within external code cells?

You should be able to use StartExternalSession to create an ongoing Python session that you can import things into before doing your main ExternalEvaluate calls.

This should also make the repeated calls a bit faster, so that is a plus.

Thanks. This was solved by unregistering one of the python distributions that I had on the system. The two methods were accessing different distributions.

Recent versions of Wolfram Language support Python virtual environments that let you specify Python packages quite easily. For example, this creates a session with a Python virtual environment that includes the sympy package:

session = StartExternalSession[<|
   "System" -> "Python",
   "Evaluator" -> <|"Dependencies" -> {"sympy"}|>,
   "SessionProlog" -> "from sympy import symbols, Eq, solve"|>]

You can then use ExternalEvaluate and call Python code, for example:

ExternalEvaluate[session, "
x, y = symbols('x y')
equation = Eq(x**5 - 4, 0)
[complex(s) for s in solve(equation, x)]"]

The output will be a list of complex numbers:

{1.31951 + 0. I, 0.40775 - 1.25493 I, 0.40775 + 1.25493 I, -1.0675 - 0.775587 I, -1.0675 + 0.775587 I}

Of course you can solve this specific example directly in the Wolfram Language as well and much more elegantly:

SolveValues[x^5 == 4.0, x]

But if you have existing Python sympy code that you would like to integrate directly into the Wolfram Language, then this is the best way to do it. I have attached a notebook with the code from this comment.

sympy-01.nb (48.8 KB)