Skip to content

Commit bd775f9

Browse files
author
Christopher Doris
committed
allow explicit conversion between Py and PyCall.PyObject
1 parent 13b2218 commit bd775f9

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/PythonCall.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,29 @@ function __init__()
107107
init_ipython()
108108
init_tables()
109109
end
110+
@require PyCall="438e738f-606a-5dbb-bf0a-cddfbfd45ab0" init_pycall(PyCall)
111+
end
112+
113+
function init_pycall(PyCall::Module)
114+
# allow explicit conversion between PythonCall.Py and PyCall.PyObject
115+
# provided they are using the same interpretr
116+
errmsg = """
117+
Conversion between `PyCall.PyObject` and `PythonCall.Py` is only possible when using the same Python interpreter.
118+
119+
There are two ways to achieve this:
120+
- Set the environment variable `JULIA_PYTHONCALL_EXE` to `"@PyCall"`. This forces PythonCall to use the same
121+
interpreter as PyCall, but PythonCall loses the ability to manage its own dependencies.
122+
- Set the environment variable `PYTHON` to `PythonCall.C.CTX.exe_path` and rebuild PyCall. This forces PyCall
123+
to use the same interpreter as PythonCall, but needs to be repeated whenever you switch Julia environment.
124+
"""
125+
@eval function Py(x::$PyCall.PyObject)
126+
C.CTX.matches_pycall::Bool || error($errmsg)
127+
return pynew(C.PyPtr($PyCall.pyreturn(x)))
128+
end
129+
@eval function $PyCall.PyObject(x::Py)
130+
C.CTX.matches_pycall::Bool || error($errmsg)
131+
return $PyCall.PyObject($PyCall.PyPtr(incref(getptr(x))))
132+
end
110133
end
111134

112135
end

0 commit comments

Comments
 (0)