Message Boards Message Boards

1
|
983 Views
|
0 Replies
|
1 Total Likes
View groups...
Share
Share this post:

How to pass values to Python?

Posted 1 year ago

I would like to pass Mathematica variable values to Python. But I found that it was not that trivial. For example, a typical way would be:

session = StartExternalSession["Python"];
l = Range[10];
res = ExternalEvaluate[session, "
l=list(<*l*>)
print(l)
l
"];
DeleteObject[session];

The results are: a Python expression [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

res
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

It seems to work. However, when I tried to define a Mathematica function with local variables:

f[l_] := Module[
  {session, res},
  session = StartExternalSession["Python"];
  res = ExternalEvaluate[session, "
l=list(<*l*>)
print(l)
l
"];
  DeleteObject[session];
  Return[res]
  ]

Clear[l]
f[Range[10]]

it didn't work. It looks like the "<* *>" notation doesn't accept local variables (in this case, l_List). I tried several patterns, but all my attempts failed in vain. After all, I needed to override the local variable l_LIst with another global variable l_List as follows.

l = Range[10];
f[Range[10]]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Did I miss something? Any suggestion would be welcome.

Attachments:
POSTED BY: Satoshi Oota
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract