Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make untyped mutating callbacks work #531

Closed
wants to merge 1 commit into from

Conversation

tkf
Copy link
Member

@tkf tkf commented Aug 20, 2018

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?

function _julia_arg(arg)
if haskey(PyCall.npy_api, :PyArray_Type) &&
pyisinstance(arg, PyCall.npy_api[:PyArray_Type])
return convert(PyArray, arg)
Copy link
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)?

f(*args)
return args
"""
@test py"apply"(fill!, zeros(3), 10)[1] == [10, 10, 10]
Copy link
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
Copy link
Member

stevengj commented Aug 20, 2018

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