Search code examples
pythonjuliabuilt-in

How can i use python built-in function like isinstance() in julia using PyCall


PyCall document says: Important: The biggest difference from Python is that object attributes/members are accessed with o[:attribute] rather than o.attribute, so that o.method(...) in Python is replaced by o:method in Julia. Also, you use get(o, key) rather than o[key]. (However, you can access integer indices via o[i] as in Python, albeit with 1-based Julian indices rather than 0-based Python indices.)

But i have no idea about which module or object to import


Solution

  • Here's a simple example to get you started

    using PyCall
    
    @pyimport numpy as np           # 'np' becomes a julia module
    
    a = np.array([[1, 2], [3, 4]])  # access objects directly under a module
                                    # (in this case the 'array' function)
                                    # using a dot operator directly on the module
    #> 2×2 Array{Int64,2}:
    #> 1  2
    #> 3  4
    
    a = PyObject(a)                 # dear Julia, we appreciate the automatic
                                    # convertion back to a julia native type, 
                                    # but let's get 'a' back in PyObject form
                                    # here so we can use one of its methods:
    #> PyObject array([[1, 2],
    #>                 [3, 4]])
    
    b = a[:mean](axis=1)            # 'a' here is a python Object (not a python 
                                    # module), so the way to access a method
                                    # or object that belongs to it is via the
                                    # pythonobject[:method] syntax.
                                    # Here we're calling the 'mean' function, 
                                    # with the appropriate keyword argument
    #> 2-element Array{Float64,1}:
    #>  1.5
    #>  3.5
    
    pybuiltin(:type)(b)             # Use 'pybuiltin' to use built-in python
                                    # commands (i.e. commands that are not 
                                    # under a module)
    #> PyObject <type 'numpy.ndarray'>
    
    pybuiltin(:isinstance)(b, np.ndarray)
    #> true