PyCall.conda
— ConstantTrue if we are using the Python distribution in the Conda package.
PyCall.PyArray
— TypePyArray(o::PyObject)
This converts an ndarray
object o
to a PyArray.
This implements a nocopy wrapper to a NumPy array (currently of only numeric types only).
If you are using pycall
and the function returns an ndarray
, you can use PyArray
as the return type to directly receive a PyArray
.
PyCall.PyDict
— TypePyDict(o::PyObject)
PyDict(d::Dict{K,V})
This returns a PyDict, which is a no-copy wrapper around a Python dictionary.
Alternatively, you can specify the return type of a pycall
as PyDict.
PyCall.PyIterator
— TypePyIterator{T}(pyobject)
Wrap pyobject::PyObject
into an iterator, that produces items of type T
. To be more precise convert(T, item)
is applied in each iteration. This can be useful to avoid automatic conversion of items into corresponding julia types.
julia> using PyCall
julia> l = PyObject([PyObject(1), PyObject(2)])
PyObject [1, 2]
julia> piter = PyCall.PyIterator{PyAny}(l)
PyCall.PyIterator{PyAny,Base.HasLength()}(PyObject [1, 2])
julia> collect(piter)
2-element Array{Any,1}:
1
2
julia> piter = PyCall.PyIterator(l)
PyCall.PyIterator{PyObject,Base.HasLength()}(PyObject [1, 2])
julia> collect(piter)
2-element Array{PyObject,1}:
PyObject 1
PyObject 2
PyCall.PyObject
— TypePyObject(juliavar)
This converts a julia variable to a PyObject, which is a reference to a Python object. You can convert back to native julia types using convert(T, o::PyObject)
, or using PyAny(o)
.
Given o::PyObject
, o[:attribute]
is equivalent to o.attribute
in Python, with automatic type conversion.
Given o::PyObject
, get(o, key)
is equivalent to o[key]
in Python, with automatic type conversion.
PyCall.PyVector
— TypePyVector(o::PyObject)
This returns a PyVector object, which is a wrapper around an arbitrary Python list or sequence object.
Alternatively, PyVector
can be used as the return type for a pycall
that returns a sequence object (including tuples).
PyCall.:≛
— Method≛(x, y)
PyPtr
based comparison of x
and y
, which can be of type PyObject
or PyPtr
.
PyCall.NoCopyArray
— MethodNoCopyArray(o::PyObject)
Convert a Python array-like object, to a Julia Array
or PermutedDimsArray
without making a copy of the data.
If the data is stored in row-major format (the default in Python/NumPy), then the returned array nca
will be a PermutedDimsArray
such that the arrays are indexed the same way in Julia and Python. i.e. nca[idxs...] == o[idxs...]
If the data is stored in column-major format then a regular Julia Array
will be returned.
Warning: This function is only lightly tested, and should be considered experimental - it may cause segmentation faults on conversion or subsequent array access, or be subtly broken in other ways. Only dense/contiguous, native endian arrays that support the Python Buffer protocol are likely be converted correctly.
PyCall.PyNULL
— MethodPyNULL()
Return a PyObject
that has a NULL
underlying pointer, i.e. it doesn't actually refer to any Python object.
This is useful for initializing PyObject
global variables and array elements before an actual Python object is available. For example, you might do const myglobal = PyNULL()
and later on (e.g. in a module __init__
function), reassign myglobal
to point to an actual object with copy!(myglobal, someobject)
. This procedure will properly handle Python's reference counting (so that the Python object will not be freed until you are done with myglobal
).
PyCall.PyReverseDims
— MethodPyReverseDims(array)
Passes a Julia array
to Python as a NumPy row-major array (rather than Julia's native column-major order) with the dimensions reversed (e.g. a 2×3×4 Julia array is passed as a 4×3×2 NumPy row-major array). This is useful for Python libraries that expect row-major data.
PyCall.PyTextIO
— MethodPyTextIO(io::IO)
PyObject(io::IO)
Julia IO streams are converted into Python objects implementing the RawIOBase interface, so they can be used for binary I/O in Python
PyCall.__pycall!
— MethodLowest level version of pycall!(ret, o, ...)
, assumes pyargsptr
and kw
have all their args set to Python values, so we can just call the function o
. Sets ret.o
to the result of the call, and returns ret::PyObject
.
PyCall._handle_error
— Method_handle_error(msg)
Throw a PyError if available, otherwise throw ErrorException. This is a hack to manually do the optimization described in https://github.com/JuliaLang/julia/issues/29688
PyCall._preserveas!
— Method_preserveas!(dest::Vector{UInt8}, (Cstring|Cwstring), x::String) :: Ptr
Copy x
as Cstring
or Cwstring
to dest
and return a pointer to dest
. Thus, this pointer is safe to use as long as dest
is protected from GC.
PyCall._pycall!
— FunctionLow-level version of pycall!(ret, o, ...)
for when kw
is already in python friendly format but you don't have the python tuple to hold the arguments (pyargsptr
). Sets ret.o
to the result of the call, and returns ret::PyObject
.
PyCall._pycall!
— MethodLow-level version of pycall!(ret, o, ...; kwargs...)
Sets ret.o
to the result of the call, and returns ret::PyObject
PyCall.anaconda_conda
— Methodanaconda_conda()
Return the path of the conda
program if PyCall is configured to use an Anaconda install (but not the Conda.jl Python), and the empty string otherwise.
PyCall.current_python
— MethodPython executable used by PyCall in the current process.
PyCall.def_py_class
— Methoddef_py_class(type_name::AbstractString, methods::Vector;
base_classes=[], getsets::Vector=[])
def_py_class
creates a Python class whose methods are implemented in Julia. @pydef
macros expand into a call to this function.
Arguments
methods
: a vector of tuples(py_name::String, jl_fun::Function)
py_name
will be a method of the Python class, which will calljl_fun
base_classes
: the Python base classes to inherit from.
Return value: the created class (::PyTypeObject
)
PyCall.f_contiguous
— Methodf_contiguous(T::Type, sz::NTuple{N,Int}, st::NTuple{N,Int})::Bool
Whether an array is in column-major (Fortran, Julia) order, and has elements stored contiguously. Any array that is f_contiguous will have identical memory layout to a Julia Array
of the same size.
sz
should be the dimensions of the array in number of elements (i.e. what size(a)
would return) st
should be the stride(s) in bytes between elements in each dimension
PyCall.get_real_method
— Methodget_real_method(obj::PyObject, name::String) -> method::Union{PyObject,Nothing}
This is a port of IPython.utils.dir2.get_real_method
: https://github.com/ipython/ipython/blob/7.9.0/IPython/utils/dir2.py
For Python 2-era https://github.com/ipython/ipython/blob/5.9.0/IPython/utils/dir2.py
PyCall.isbuftype
— Methodisbuftype(o::Union{PyObject,PyPtr})
Returns true
if the python object o
supports the buffer protocol as a strided array. false
if not.
PyCall.ispynull
— Methodispynull(o::PyObject)
Test where o
contains a NULL
pointer to a Python object, i.e. whether it is equivalent to a PyNULL()
object.
PyCall.pybuiltin
— Methodpybuiltin(s::AbstractString)
Look up a string or symbol s
among the global Python builtins. If s
is a string it returns a PyObject, while if s
is a symbol it returns the builtin converted to PyAny
.
PyCall.pybytes
— Methodpybytes(b::Union{String,DenseVector{UInt8}})
Convert b
to a Python bytes
object. This differs from the default PyObject(b)
conversion of String
to a Python string (which may fail if b
does not contain valid Unicode), or from the default conversion of a Vector{UInt8}
to a bytearray
object (which is mutable, unlike bytes
).
PyCall.pycall!
— Methodpycall!(ret::PyObject, o::Union{PyObject,PyPtr}, returntype::Type, args...; kwargs...)
Set ret
to the result of pycall(o, returntype, args...; kwargs)
and return convert(returntype, ret)
. Avoids allocating an extra PyObject for ret
. See pycall
for other details.
PyCall.pycall
— Methodpycall(o::Union{PyObject,PyPtr}, returntype::TypeTuple, args...; kwargs...)
Call the given Python function (typically looked up from a module) with the given args... (of standard Julia types which are converted automatically to the corresponding Python types if possible), converting the return value to returntype (use a returntype of PyObject to return the unconverted Python object reference, or of PyAny to request an automated conversion)
PyCall.pydecref
— Methodpydecref(o::PyBuffer)
Release the reference to buffer o
N.b. As per https://docs.python.org/3/c-api/buffer.html#c.PyBufferRelease, It is an error to call this function on a PyBuffer that was not obtained via the python c-api function `PyObjectGetBuffer()`, unless o.obj is a PyPtr(C_NULL)
PyCall.pyeval
— Functionpyeval(s::AbstractString, returntype::TypeTuple=PyAny, locals=PyDict{AbstractString, PyObject}(),
input_type=Py_eval_input; kwargs...)
This evaluates s
as a Python string and returns the result converted to rtype
(which defaults to PyAny
). The remaining arguments are keywords that define local variables to be used in the expression.
For example, pyeval("x + y", x=1, y=2)
returns 3.
PyCall.pyfunction
— Methodpyfunction(f, argtypes...; kwtypes...)
Create a Python object that wraps around the Julia function (or callable object) f
. Unlike PyObject(f)
, this allows you to specify the argument types that the Julia function expects — giving you more control and potentially better performance.
kwtypes...
should be a set of somekeyword=SomeType
arguments giving the desired Julia type for each keyword somekeyword
. Unspecified keywords are converted to PyAny
(i.e. auto-detected) by default.
The return value ret = f(...)
is still converted back to a Python object by PyObject(ret)
. If you want a different return-type conversion than the default of PyObject(ret)
, you can instead call pyfunctionret
.
PyCall.pyfunctionret
— Methodpyfunctionret(f, returntype, argtypes...; kwtypes...)
Like pyfunction
, but also lets you specify the returntype
for conversion back to Python. In particular, if ret = f(...)
is the return value of f
, then it is converted to Python via PyObject(returntype(ret))
.
If returntype
is Any
, then ret
is not converted to a "native" Python type at all, and is instead converted to a "wrapped" Julia object in Python. If returntype
is nothing
, then the return value is discarded and nothing
is returned to Python.
PyCall.pygui
— Methodpygui()
Return the current GUI toolkit as a symbol.
PyCall.pygui_start
— Functionpygui_start(gui::Symbol = pygui())
Start the event loop of a certain toolkit.
The argument gui
defaults to the current default GUI, but it could be :wx
, :gtk
, :gtk3
, :tk
, or :qt
.
PyCall.pygui_stop
— Functionpygui_stop(gui::Symbol = pygui())
Stop any running event loop for gui. The gui
argument defaults to current default GUI.
PyCall.pyimport
— Methodpyimport(s::AbstractString)
Import the Python module s
(a string or symbol) and return a pointer to it (a PyObject
). Functions or other symbols in the module may then be looked up by s[name] where name is a string (for the raw PyObject) or symbol (for automatic type-conversion). Unlike the @pyimport macro, this does not define a Julia module and members cannot be accessed with s.name
PyCall.pyimport_conda
— Functionpyimport_conda(modulename, condapkg, [channel])
Returns the result of pyimport(modulename)
if possible. If the module is not found, and PyCall is configured to use the Conda Python distro (via the Julia Conda package), then automatically install condapkg
via Conda.add(condapkg)
and then re-try the pyimport
. Other Anaconda-based Python installations are also supported as long as their conda
program is functioning.
If PyCall is not using Conda and the pyimport
fails, throws an exception with an error message telling the user how to configure PyCall to use Conda for automated installation of the module.
The third argument, channel
is an optional Anaconda "channel" to use for installing the package; this is useful for packages that are not included in the default Anaconda package listing.
PyCall.pyimport_e
— Methodpyimport_e(s::AbstractString)
Like pyimport(s)
, but returns an ispynull(o) == true
object if the module cannot be imported rather than throwing an error.
PyCall.pyrepr
— Methodpyrepr(o::PyObject)
Return a string representation of o
corresponding to repr(o)
in Python.
PyCall.pyreturn
— Methodpyreturn(x) :: PyPtr
Prepare PyPtr
from x
for passing it to Python. If x
is already a PyObject
, the refcount is incremented. Otherwise a PyObject
wrapping/converted from x
is created.
PyCall.pystealref!
— Method"Steal" a reference from a PyObject: return the raw PyPtr, while setting the corresponding o.o
field to NULL
so that no decref will be performed when o
is garbage collected. (This means that you can no longer use o
.) Used for passing objects to Python.
PyCall.pystr
— Methodpystr(o::PyObject)
Return a string representation of o
corresponding to str(o)
in Python.
PyCall.pystring
— Methodpystring(o::PyObject)
Return a string representation of o
. Normally, this corresponds to repr(o)
in Python, but unlike repr
it should never fail (falling back to str
or to printing the raw pointer if necessary).
PyCall.python_cmd
— Functionpython_cmd(args::Cmd = ``; venv, python) :: Cmd
Create an appropriate Cmd
for running Python program with command line arguments args
.
Keyword Arguments
venv::String
: The path of a virtualenv to be used instead of the default environment with which PyCall isconfigured.python::String
: The path to the Python executable.venv
is ignored when this argument is specified.
PyCall.pytype_mapping
— Methodpytype_mapping(pytype, jltype)
Given a Python type object pytype
, tell PyCall to convert it to jltype
in PyAny(object)
conversions.
PyCall.pytype_query
— Functionpytype_query(o::PyObject, default=PyObject)
Given a Python object o
, return the corresponding native Julia type (defaulting to default
) that we convert o
to in PyAny(o)
conversions.
PyCall.pywrap
— Functionpywrap(o::PyObject)
This returns a wrapper w
that is an anonymous module which provides (read) access to converted versions of o's members as w.member.
For example, @pyimport module as name
is equivalent to const name = pywrap(pyimport("module"))
If the Python module contains identifiers that are reserved words in Julia (e.g. function), they cannot be accessed as w.member
; one must instead use w.pymember(:member)
(for the PyAny conversion) or w.pymember("member") (for the raw PyObject).
PyCall.setdata!
— MethodUpdate the data ptr of the a
to point to the buffer exposed by o
through the Python buffer interface
PyCall.showerror_string
— Methodshowerror_string(e) :: String
Convert output of showerror
to a String
. Since this function may be called via Python C-API, it tries to not throw at all cost.
PyCall.@py_str
— Macropy".....python code....."
Evaluate the given Python code string in the main Python module.
If the string is a single line (no newlines), then the Python expression is evaluated and the result is returned. If the string is multiple lines (contains a newline), then the Python code is compiled and evaluated in the __main__
Python module and nothing is returned.
If the o
option is appended to the string, as in py"..."o
, then the return value is an unconverted PyObject
; otherwise, it is automatically converted to a native Julia type if possible.
Any $var
or $(expr)
expressions that appear in the Python code (except in comments or string literals) are evaluated in Julia and passed to Python via auto-generated global variables. This allows you to "interpolate" Julia values into Python code.
Similarly, ny $$var
or $$(expr)
expressions in the Python code are evaluated in Julia, converted to strings via string
, and are pasted into the Python code. This allows you to evaluate code where the code itself is generated by a Julia expression.
PyCall.@pycall
— Macro@pycall func(args...)::T
Convenience macro which turns func(args...)::T
into pycall(func, T, args...)
PyCall.@pydef
— Macro@pydef
creates a Python class whose methods are implemented in Julia. For instance,
P = pyimport("numpy.polynomial")
@pydef type Doubler <: P.Polynomial
__init__(self, x=10) = (self.x = x)
my_method(self, arg1::Number) = arg1 + 20
x2.get(self) = self.x * 2
x2.set!(self, new_val) = (self.x = new_val / 2)
end
Doubler().x2
is essentially equivalent to the following Python code:
class Doubler(numpy.polynomial.Polynomial):
def __init__(self, x=10):
self.x = x
def my_method(self, arg1): return arg1 + 20
@property
def x2(self): return self.x * 2
@x2.setter
def x2(self, new_val):
self.x = new_val / 2
Doubler().x2
The method arguments and return values are automatically converted between Julia and Python. All Python special methods are supported (__len__
, __add__
, etc.)
@pydef
allows for multiple inheritance of Python types:
@pydef type SomeType <: (BaseClass1, BaseClass2)
...
end
Multiple dispatch works, too:
x2.set!(self, new_x::Int) = ...
x2.set!(self, new_x::Float64) = ...
PyCall.@pydef_object
— Macro@pydef_object
is like @pydef
, but it returns the metaclass as a PyObject
instead of binding it to the class name. It's side-effect-free, except for the definition of the class methods.
PyCall.@pyinclude
— Macro@pyinclude(filename)
Execute the Python script in the file filename
as if it were in a py""" ... """
block, e.g. so that any globals defined in filename
are available to subsequent py"..."
evaluations.
(Unlike py"..."
, however, @pyinclude
does not interpolate Julia variables into $var
expressions — the filename
script must be pure Python.)
PyCall.@pyraise
— Macro@pyraise e
Throw the exception e
to Python, attaching a backtrace. This macro should only be used in a catch
block so that catch_backtrace()
is valid.
PyCall.@pywith
— Macro@pywith
Mimics a Python 'with' statement. Usage:
@pywith EXPR[::TYPE1] [as VAR[::TYPE2]] begin BLOCK end
TYPE1/TYPE2 can optionally be used to override automatic conversion to Julia types for both the context manager and variable in cases where this is not desired.