pyjulia icon indicating copy to clipboard operation
pyjulia copied to clipboard

PyJulia Custom Structure Dispatch

Open McCastles opened this issue 3 years ago • 1 comments

Hello, I've got a quistion as for the PyJulia functionality. How do I dispatch a Julia method for different objects defined in Python?

I assume the existence of an underlying mapping between native Python and Julia types: int -> Integer, float -> Float64, but at the same time np.array -> Array, which makes me think that I can customize this sort of mapping and connect MyClassPy -> MyClassJulia. Is that so?

Thank you in advance!

example.py

class MyClassA:
    pass

class MyClassB:
    pass

from julia import Julia
julia = Julia()
julia.eval("@eval Main import Base.MainInclude: include")
from julia import Main
Main.include("example.jl")

foo(MyClassA()) # "Dispatched to MyClassA version"

foo(MyClassB()) # "Dispatched to MyClassB version"

example.jl

# How can I access MyClassA and MyClassB types in Julia?
some_magic_way_to_include_structures_defined_in_python() 

function foo( custom_pyobject :: MyClassA )
    println("Dispatched to MyClassA version")
end

function foo( custom_pyobject :: MyClassB )
    println("Dispatched to MyClassB version")
end

McCastles avatar Oct 26 '22 10:10 McCastles