JuliaPy / PyCall.jl

Package to call Python functions from the Julia language
MIT License
1.45k stars 186 forks source link

How to Convert line "From <module> import <function>" ? #1001

Closed glanzkaiser closed 1 year ago

glanzkaiser commented 1 year ago

Hi all,

I am using JupyterLab with Julia kernel version 1.7.3 and I want to use PyCall to call a Python module to create venn's diagram.

using PyCall

plt = pyimport("matplotlib.pyplot")
from matplotlib_venn import venn3

# Custom text labels: change the label of group A
v=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ('Group A', 'Group B', 'Group C'))
v.get_label_by_id('A').set_text('My Favourite group!')
plt.show()

I get this error: syntax: extra token "matplotlib_venn" after end of expression Stacktrace: [1] top-level scope @ In[43]:5 [2] eval @ ./boot.jl:373 [inlined] [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String) @ Base ./loading.jl:1196

How to fix this? I think the problem is the line with matplotlib_venn.

stevengj commented 1 year ago
venn3 = pyimport("matplotlib_venn").venn3

(You can't just drop Python syntax into Julia code.)

glanzkaiser commented 1 year ago

I am using this code now:

using PyCall

py"""
plt = pyimport("matplotlib.pyplot")
venn3 = pyimport("matplotlib_venn").venn3

# Custom text labels: change the label of group A
v=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ('Group A', 'Group B', 'Group C'))
v.get_label_by_id('A').set_text('My Favourite group!')
"""
plt.show()

Got error: PyError ($(Expr(:escape, :(ccall(#= /home/browni/.julia/packages/PyCall/7a7w0/src/pyeval.jl:38 =# @pysym(:PyEval_EvalCode), PyPtr, (PyPtr, PyPtr, PyPtr), o, globals, locals))))) <class 'NameError'> NameError("name 'pyimport' is not defined") File "/home/browni/.julia/packages/PyCall/7a7w0/src/pyeval.jl", line 1, in const Py_single_input = 256 # from Python.h

stevengj commented 1 year ago

Don't use py"....", that's only for executing snippets literal Python code. pyimport is a Julia function. Do something like:

using PyCall
plt = pyimport("matplotlib.pyplot")
venn3 = pyimport("matplotlib_venn").venn3

# Custom text labels: change the label of group A
v=venn3(subsets = (10, 8, 22, 6,9,4,2), set_labels = ("Group A", "Group B", "Group C"))
v.get_label_by_id("A").set_text("My Favourite group!")

Note that there is no py"..." since this is Julia code. (Note also that Julia strings use only double quotes, not single quotes ala Python.)