Skip to content

Make untyped mutating callbacks work - #531

Closed
tkf wants to merge 1 commit into
JuliaPy:masterfrom
tkf:mutating-callback
Closed

tkf wants to merge 1 commit into
JuliaPy:masterfrom
tkf:mutating-callback

Conversation

@tkf

@tkf tkf commented Aug 20, 2018

Copy link
Copy Markdown
Member

I'm writing this PR to start a discussion: Do we want untyped Julia callback to be able to mutate Python objects? That is to say, do we want the following code to work?

py"""
def apply(f, *args):
    f(*args)
    return args
"""
@test py"apply"(fill!, zeros(3), 10)[1] == [10, 10, 10]

I got here while trying to fix pyjulia bug I observed in JuliaPy/pyjulia#183 (comment)

It requires some run-time introspection and hard-coding many mutable Python objects (I only did it for Numpy array at the moment). Is there a better way to do it? Do we want this in the first place?

Comment thread src/callback.jl
function _julia_arg(arg)
if haskey(PyCall.npy_api, :PyArray_Type) &&
pyisinstance(arg, PyCall.npy_api[:PyArray_Type])
return convert(PyArray, arg)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it makes sense to move the code above inside convert(::Type{PyAny}, o::PyObject)?

Comment thread test/runtests.jl
f(*args)
return args
"""
@test py"apply"(fill!, zeros(3), 10)[1] == [10, 10, 10]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I should have called it apply_inplace or sth to avoid confusion with Python 2 builtin apply.

@stevengj

stevengj commented Aug 20, 2018 •

Copy link
Copy Markdown
Member

Julia callbacks mutating Python objects will only work (in general) if you use pyfunction to control how the Python arguments are converted for the Julia caller.

For example:

julia> pyfill! = pyfunction(fill!, PyVector, PyAny)
PyObject <PyCall.jlwrap PyCall.FuncWrapper{Tuple{PyVector,PyAny},typeof(fill!)}(fill!, Dict{Symbol,Any}())>

julia> v = py"[1,2,3,4]"o
PyObject [1, 2, 3, 4]

julia> pyfill!(v, 7)
4-element Array{Int64,1}:
 7
 7
 7
 7

julia> v
PyObject [7, 7, 7, 7]

I think this is the right way to do it — for example, you can't rely on everything being a NumPy array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants