The Julia module PythonCall
To get started, just do using PythonCall
. There are two main ways to use this module:
Way 1: There is a collection of macros for directly executing Python code, interpolating Julia values in and extracting Julia values out. For example @pyv `$x+1`::Int
adds x
to 1
in Python and converts the result to an Int
.
Way 2: There is a collection of functions which typically produce and consume Python objects. The previous example can be implemented as pyadd(Int, x, 1)
or pyconvert(Int, PyObject(x)+1)
.
In all cases, when a Julia value needs to be passed to Python, it will be converted according to this table.
When a Python value is returned to Julia, by default it will be as a PyObject
. Most functions provide an optional way to specify the return type, in which case it will be converted according to this table.
You can also specify one of the wrapper types as a return type.
PyObject
PythonCall.PyObject
— TypePyObject(x)
Convert x
to a Python object.
This is the default type returned by most API functions.
It supports attribute access (x.attr
), indexing (x[i,j]
, delete!(x, i, j)
), calling x(a, b, kw=c)
, length
, iteration (yielding PyObject
s), comparisons to other PyObject
s (x == y
), and arithmetic with other PyObject
s and Number
s (x + y
, x * 3
).
Note that comparisons between PyObject
s (==
, ≠
, ≤
, etc.) return PyObject
, except isequal
and isless
which return Bool
. Use pyeq
and friends to return Bool
.
A number of special properties are also defined for convenience to convert the object to another type. To avoid clashes with object attributes, they all have the prefix jl!
.
x.jl!(T)
ispyconvert(T, x)
x.jl!i
ispyconvert(Int, x)
x.jl!b
ispytruth(x)
x.jl!s
ispystr(String, x)
.x.jl!r
ispyrepr(String, x)
.x.jl!f
ispyconvert(Float64, x)
x.jl!c
ispyconvert(Complex{Float64}, x)
x.jl!iter(T=PyObject)
isPyIterable{T}(x)
x.jl!list(T=PyObject)
isPyList{T}(x)
x.jl!set(T=PyObject)
isPySet{T}(x)
x.jl!dict(K=PyObject, V=PyObject)
isPyDict{K,V}(x)
x.jl!io(...)
isPyIO(x; ...)
x.jl!pandasdf(...)
isPyPandasDataFrame(x; ...)
x.jl!buffer(...)
isPyBuffer(x, ...)
x.jl!array(...)
isPyArray{...}(x)
x.jl!vector(...)
isPyVector{...}(x)
x.jl!matrix(...)
isPyMatrix{...}(x)
Execute Python code
These macros are used to execute or evaluate Python code. The main differences between them are in whether/how any values are extracted out again.
Note to package writers. These all expect there to be a variable pyglobals
in scope, which is a Python dictionary giving the global scope. For convenience, this module exports such a variable so that these macros work in the REPL. However other packages should define their own global scope by defining const pyglobals = PyDict()
. You can alternatively define const pyglobals = PythonCall.pylazyobject(()->pyimport("some_module").__dict__)
to use the global scope of an existing Python module.
PythonCall.@py
— Macro@py `...` [locals] [var=val, ...]
Execute the given Python code.
Julia values can be interpolated using the usual $(...)
syntax.
Additionally, assignment to interpolations is supported: e.g. $(x::T) = ...
will convert the right hand side to a T
and assign it to x
.
- Currently only single assignment is supported. Multiple assignment (
$x, $y = ...
) or mutating assignment ($x += ...
) will not be recognized. - What actually happens is that the assignment is to a temporary Python variable, which is then read when execution successfully finishes. Hence if an exception occurs, no assignments will happen.
The globals are pyglobals
. The locals are locals
, if given, otherwise a temporary scope is created. Extra values to be interted into the scope can be given with extra var=val
arguments.
PythonCall.@pyv
— Macro@pyv `...`[::rettype] [locals] [var=val, ...]
Evaluate the given Python expression and return its value.
Julia values can be interpolated using the usual $(...)
syntax.
The globals are pyglobals
. The locals are locals
, if given, otherwise a temporary scope is created. Extra values to be interted into the scope can be given with extra var=val
arguments.
The result is converted to a rettype
, which defaults to PyObject
.
PythonCall.@pyg
— Macro@pyg `...` [var=val, ...]
Execute the given Python code in the global scope.
This is simply shorthand for @py `...` pyglobals
(see @py
).
PythonCall.@pya
— Macro@pya `...`[::rettype] [locals] [var=val, ...]
Execute the given Python code and return ans
.
This is the same as @py ...
except that the variable ans
is extracted from the scope and returned.
PythonCall.@pyr
— Macro@pyr `...`[::rettype] [locals] [var=val, ...]
Execute the given Python code in a function and return its return value.
Essentially equivalent to @pya `def result(): ...; ans = result()`
.
Python functions
Construct Python objects
These functions convert Julia values into Python objects of standard types.
PythonCall.pynone
— Functionpynone([T=PyObject]) :: T
Equivalent to None
in Python.
PythonCall.pybool
— Functionpybool([T=PyObject,] ...) :: T
Equivalent to bool(...)
in Python.
PythonCall.pyint
— Functionpyint([T=PyObject,] ...) :: T
Equivalent to int(...)
in Python.
PythonCall.pyfloat
— Functionpyfloat([T=PyObject,] ...) :: T
Equivalent to float(...)
in Python.
PythonCall.pystr
— Functionpystr([T=PyObject,] x) :: T
Equivalent to str(x)
in Python.
PythonCall.pybytes
— Functionpybytes([T=PyObject,] x) :: T
Equivalent to str(x)
in Python.
PythonCall.pytuple
— Functionpytuple([T=PyObject,] [x]) :: T
Create a Python tuple
from the elements of iterable x
.
If x
is a Python object, this is equivalent to tuple(x)
in Python.
PythonCall.pylist
— Functionpylist([T=PyObject,] [x]) :: T
Create a Python list
from the elements of iterable x
.
If x
is a Python object, this is equivalent to list(x)
in Python.
PythonCall.pycollist
— Functionpycollist([T=PyObject,] x::AbstractArray) :: T
Create a nested Python list
-of-list
s from the elements of x
. For matrices, this is a list of columns.
PythonCall.pyrowlist
— Functionpyrowlist([T=PyObject,] x::AbstractArray) :: T
Create a nested Python list
-of-list
s from the elements of x
. For matrices, this is a list of rows.
PythonCall.pyset
— Functionpyset([T=PyObject,] [x]) :: T
Create a Python set
from the elements of iterable x
.
If x
is a Python object, this is equivalent to set(x)
in Python.
PythonCall.pyfrozenset
— Functionpyfrozenset([T=PyObject,] [x]) :: T
Create a Python frozenset
from the elements of iterable x
.
If x
is a Python object, this is equivalent to frozenset(x)
in Python.
PythonCall.pydict
— Functionpydict([T=PyObject,] [x]) :: T
pydict([T=PyObject;] key=value, ...)
Create a Python dict
from the given key-value pairs in x
or keyword arguments.
If x
is a Python object, this is equivalent to dict(x)
in Python.
PythonCall.pyslice
— Functionpyslice([T=PyObject,] [start,] stop, [step]) :: T
Equivalent to slice(start, stop, step)
in Python (or start:stop:step
while indexing).
PythonCall.pyellipsis
— Functionpyellipsis([T=PyObject]) :: T
Equivalent to Ellipsis
in Python (or ...
while indexing).
PythonCall.pynotimplemented
— Functionpynotimplemented([T=PyObject]) :: T
Equivalent to NotImplemented
in Python.
PythonCall.pymethod
— Functionpymethod([T=PyObject,] x) :: T
Convert x
to a Python instance method.
PythonCall.pytype
— Functionpytype([T=PyObject,] x) :: T
Equivalent to type(x)
in Python.
pytype([T=PyObject,] name, bases, dict) :: T
Equivalent to type(name, bases, dict)
in Python.
Wrap Julia values
These functions wrap Julia values into Python objects, documented here.
PythonCall.pyjl
— Functionpyjl([T=PyObject,] x)
Wrap x
as a Python juliacall.AnyValue
(or subclass) object.
PythonCall.pyjlraw
— Functionpyjlraw([T=PyObject,] x)
Wrap x
as a Python juliacall.RawValue
object.
PythonCall.pyisjl
— Functionpyisjl(o)
True if o
is a juliacall.ValueBase
object.
PythonCall.pyjlgetvalue
— Functionpyjlgetvalue()
PythonCall.pytextio
— Functionpytextio([T=PyObject], io::IO) :: T
Convert io
to a Python text IO stream, specifically a juliacall.TextIOValue
.
PythonCall.pyrawio
— Functionpyrawio([T=PyObject], io::IO) :: T
Convert io
to a Python raw (unbuffered byte) IO stream, specifically a juliacall.RawIOValue
.
PythonCall.pybufferedio
— Functionpybufferedio([T=PyObject], io::IO) :: T
Convert io
to a Python buffered byte IO stream, specifically a juliacall.BufferedIOValue
.
Python builtins
PythonCall.pyconvert
— Functionpyconvert(T, x) :: T
Convert Python object x
to a T
.
PythonCall.pyimport
— Functionpyimport([T=PyObject,] name) :: T
pyimport([T=PyObject,] name=>attr) :: T
pyimport([T=PyObject,] name=>(attr,...)) :: Tuple{T,...}
Imports and returns the Python module name
.
If additionally attr
is given, the given attribute of the module is returned instead. It may also be a tuple of attributes.
If several arguments are given, each one is imported and a tuple is returned.
PythonCall.pywith
— Functionpywith(f, o, d=nothing)
Equivalent to with o as x: f(x)
in Python, where x
is a PyObject
.
On success, the value of f(x)
is returned. If an exception occurs but is suppressed then d
is returned.
PythonCall.pyis
— Functionpyis(x, y) :: Bool
Equivalent to x is y
in Python.
PythonCall.pyrepr
— Functionpyrepr([T=PyObject,] x) :: T
Equivalent to repr(x)
in Python.
PythonCall.pyhasattr
— Functionpyhasattr(x, k) :: Bool
Equivalent to hasattr(x, k)
in Python, returned as a Bool
.
PythonCall.pygetattr
— Functionpygetattr([T=PyObject,] x, k) :: T
Equivalent to x.k
or getattr(x, k)
in Python.
PythonCall.pysetattr
— Functionpysetattr(x, k, v)
Equivalent to x.k = v
or setattr(x, k, v)
in Python, but returns x
.
PythonCall.pydir
— Functionpydir([T=PyObject,] x) :: T
Equivalent to dir(x)
in Python.
PythonCall.pycall
— Functionpycall([T=PyObject,] f, args...; kwargs...) :: T
Equivalent to f(*args, **kwargs)
in Python.
PythonCall.pylen
— Functionpylen(x) :: Integer
Equivalent to len(x)
in Python.
PythonCall.pycontains
— Functionpycontains(x, v) :: Bool
Equivalent to v in x
in Python.
PythonCall.pyin
— Functionpyin(v, x) :: Bool
Equivalent to v in x
in Python.
PythonCall.pygetitem
— Functionpygetitem([T=PyObject,] x, k) :: T
Equivalent to x[k]
or getitem(x, k)
in Python.
PythonCall.pysetitem
— Functionpysetitem(x, k, v)
Equivalent to x[k] = v
or setitem(x, k, v)
in Python, but returns x
.
PythonCall.pydelitem
— Functionpydelitem(x, k)
Equivalent to del x[k]
or delitem(x, k)
in Python, but returns x.
PythonCall.pytruth
— Functionpytruth(x) :: Bool
The truthyness of x
, equivalent to bool(x)
or not not x
in Python, or to pybool(Bool, x)
.
PythonCall.pyissubclass
— Functionpyissubclass(x, y) :: Bool
Equivalent to issubclass(x, y)
in Python.
PythonCall.pyisinstance
— Functionpyisinstance(x, y) :: Bool
Equivalent to isinstance(x, y)
in Python.
PythonCall.pyhash
— Functionpyhash(x) :: Integer
Equivalent to hash(x)
in Python.
PythonCall.pyiter
— Functionpyiter([T=PyObject] x) :: T
Equivalent to iter(x)
in Python.
Numbers
PythonCall.pyeq
— Functionpyeq([T=PyObject,] x, y) :: T
Equivalent to x == y
in Python.
PythonCall.pyne
— Functionpyne([T=PyObject,] x, y) :: T
Equivalent to x != y
in Python.
PythonCall.pyle
— Functionpyle([T=PyObject,] x, y) :: T
Equivalent to x <= y
in Python.
PythonCall.pylt
— Functionpylt([T=PyObject,] x, y) :: T
Equivalent to x < y
in Python.
PythonCall.pyge
— Functionpyge([T=PyObject,] x, y) :: T
Equivalent to x >= y
in Python.
PythonCall.pygt
— Functionpygt([T=PyObject,] x, y) :: T
Equivalent to x > y
in Python.
PythonCall.pyadd
— Functionpyadd([T=PyObject,] x, y) :: T
Equivalent to x + y
in Python.
PythonCall.pyiadd
— Functionpyiadd([T=typeof(x),] x, y) :: T
x = pyiadd(x, y)
is equivalent to x += y
in Python.
PythonCall.pysub
— Functionpysub([T=PyObject,] x, y) :: T
Equivalent to x - y
in Python.
PythonCall.pyisub
— Functionpyisub([T=typeof(x),] x, y) :: T
x = pyisub(x, y)
is equivalent to x -= y
in Python.
PythonCall.pymul
— Functionpymul([T=PyObject,] x, y) :: T
Equivalent to x * y
in Python.
PythonCall.pyimul
— Functionpyimul([T=typeof(x),] x, y) :: T
x = pyimul(x, y)
is equivalent to x *= y
in Python.
PythonCall.pymatmul
— Functionpymatmul([T=PyObject,] x, y) :: T
Equivalent to x @ y
in Python.
PythonCall.pyimatmul
— Functionpyimatmul([T=typeof(x),] x, y) :: T
x = pyimatmul(x, y)
is equivalent to x @= y
in Python.
PythonCall.pyfloordiv
— Functionpyfloordiv([T=PyObject,] x, y) :: T
Equivalent to x // y
in Python.
PythonCall.pyifloordiv
— Functionpyifloordiv([T=typeof(x),] x, y) :: T
x = pyifloordiv(x, y)
is equivalent to x //= y
in Python.
PythonCall.pytruediv
— Functionpytruediv([T=PyObject,] x, y) :: T
Equivalent to x / y
in Python.
PythonCall.pyitruediv
— Functionpyitruediv([T=typeof(x),] x, y) :: T
x = pyitruediv(x, y)
is equivalent to x /= y
in Python.
PythonCall.pymod
— Functionpymod([T=PyObject,] x, y) :: T
Equivalent to x % y
in Python.
PythonCall.pyimod
— Functionpyimod([T=typeof(x),] x, y) :: T
x = pyimod(x, y)
is equivalent to x %= y
in Python.
PythonCall.pydivmod
— Functionpydivmod([T=PyObject,] x, y) :: T
Equivalent to divmod(x, y)
in Python.
PythonCall.pylshift
— Functionpylshift([T=PyObject,] x, y) :: T
Equivalent to x << y
in Python.
PythonCall.pyilshift
— Functionpyilshift([T=typeof(x),] x, y) :: T
x = pyilshift(x, y)
is equivalent to x <<= y
in Python.
PythonCall.pyrshift
— Functionpyrshift([T=PyObject,] x, y) :: T
Equivalent to x >> y
in Python.
PythonCall.pyirshift
— Functionpyirshift([T=typeof(x),] x, y) :: T
x = pyirshift(x, y)
is equivalent to x >>= y
in Python.
PythonCall.pyand
— Functionpyand([T=PyObject,] x, y) :: T
Equivalent to x & y
in Python.
PythonCall.pyiand
— Functionpyiand([T=typeof(x),] x, y) :: T
x = pyiand(x, y)
is equivalent to x &= y
in Python.
PythonCall.pyor
— Functionpyor([T=PyObject,] x, y) :: T
Equivalent to x | y
in Python.
PythonCall.pyior
— Functionpyior([T=typeof(x),] x, y) :: T
x = pyior(x, y)
is equivalent to x |= y
in Python.
PythonCall.pyxor
— Functionpyxor([T=PyObject,] x, y) :: T
Equivalent to x ^ y
in Python.
PythonCall.pyixor
— Functionpyixor([T=typeof(x),] x, y) :: T
x = pyixor(x, y)
is equivalent to x ^= y
in Python.
PythonCall.pypow
— Functionpypow([T=PyObject,] x, y, [z]) :: T
Equivalent to x**y
or pow(x, y, z)
in Python.
PythonCall.pyipow
— Functionpyipow([T=typeof(x),] x, y, [z]) :: T
x = pyipow(x, y)
is equivalent to x **= y
in Python.
PythonCall.pyneg
— Functionpyneg([T=typeof(x),] x) :: T
Equivalent to -x
in Python.
PythonCall.pypos
— Functionpypos([T=typeof(x),] x) :: T
Equivalent to +x
in Python.
PythonCall.pyabs
— Functionpyabs([T=typeof(x),] x) :: T
Equivalent to abs(x)
in Python.
PythonCall.pyinv
— Functionpyinv([T=typeof(x),] x) :: T
Equivalent to -x
in Python.
Wrapper types
PythonCall.PyList
— TypePyList{T=PyObject}([o])
Wrap the Python list o
(or anything satisfying the sequence interface) as a Julia vector with elements of type T
.
If o
is not given, an empty list is created.
PythonCall.PySet
— TypePySet{T=PyObject}([o])
Wrap the Python set o
(or anything satisfying the set interface) as a Julia set with elements of type T
.
If o
is not given, an empty set is created.
PythonCall.PyDict
— TypePyDict{K=PyObject, V=PyObject}([o])
Wrap the Python dictionary o
(or anything satisfying the mapping interface) as a Julia dictionary with keys of type K
and values of type V
.
If o
is not given, an empty dict is created.
PythonCall.PyIterable
— TypePyIterable{T=PyObject}(o)
Wrap the Python object o
into a Julia object which iterates values of type T
.
PythonCall.PyArray
— TypePyArray{R,N,T,M,L}(o) :: AbstractArray{T,N}
Interpret the Python array o
as a Julia array.
The input may be anything supporting the buffer protocol or the numpy array interface. This includes bytes
, bytearray
, array.array
, numpy.ndarray
, pandas.Series
.
All type parameters are optional:
R
is the type of elements of the underlying buffer.N
is the number of dimensions.T
is the element type.M
is true if the array is mutable.L
is true if the array supports fast linear indexing.
There are alias types with names of the form Py[Mutable/Immutable/][Linear/Cartesian/][Array/Vector/Matrix]
.
PythonCall.PyBuffer
— TypePyBuffer(o, [flags=C.PyBUF_FULL_RO])
A reference to the underlying buffer of o
, if it satisfies the buffer protocol.
Has the following properties:
buf
: Pointer to the data.obj
: The exporting object (usuallyo
).len
: The length of the buffer in bytes.readonly
: True if the buffer is immutable.itemsize
: The size of each element.format
: The struct-syntax format of the element type.ndim
: The number of dimensions.shape
: The length of the buffer in each dimension.strides
: The strides (in bytes) of the buffer in each dimension.suboffsets
: For indirect arrays. See the buffer protocol documentation.isccontiguous
: True if the buffer is C-contiguous (e.g. numpy arrays).isfcontiguous
: True if the buffer is Fortran-contiguous (e.g. Julia arrays).eltype
: The element type.
PythonCall.PyIO
— TypePyIO(o; own=false, text=missing, buflen=4096)
Wrap the Python byte-based IO stream o
as a Julia IO stream.
When this goes out of scope and is finalized, it is automatically flushed. If own=true
then it is also closed.
If text=false
then o
must be a binary stream and arbitrary binary I/O is possible. If text=true
then o
must be a text stream and only UTF-8 must be written (i.e. use print
not write
). If text
is not specified then it is chosen automatically. If o
is a text stream and you really need a binary stream, then often PyIO(o.buffer)
will work.
For efficiency, reads and writes are buffered before being sent to o
. The size of the buffer is buflen
.
PythonCall.PyPandasDataFrame
— TypePyPandasDataFrame(o; indexname=:index, columntypes=(), copy=false)
Wrap the Pandas dataframe o
as a Julia table.
This object satisfies the Tables.jl
and TableTraits.jl
interfaces.
indexname
: The name of the index column when converting this to a table, and may benothing
to exclude the index.columntypes
: An iterable ofcolumnname=>type
or[columnnames...]=>type
pairs, used when converting to a table.copy
: True to copy columns on conversion.
PythonCall.PyCode
— TypePyCode(code::String, filename::String, mode::Symbol)
A Python code object, representing the compiled contents of code
.
The filename
is used for exception printing. The mode must be :exec
or :eval
.
PythonCall.@py_cmd
— Macropy`...` :: PyCode
Literal syntax for a compiled PyCode
object in "exec" mode.
Suitable for passing to Python's exec
function.
PythonCall.@pyv_cmd
— Macropyv`...` :: PyCode
Literal syntax for a compiled PyCode
object in "eval" mode.
Suitable for passing to Python's eval
function.
PythonCall.PyInternedString
— TypePyInternedString(x::String)
Convert x
to an interned Python string.
This can provide a performance boost when using strings to index dictionaries or get attributes.
See also @pystr_str
.
PythonCall.@pystr_str
— Macropystr"..." :: PyInternedString
Literal syntax for an interned Python string.
PythonCall.PyException
— TypePyException <: Exception
Represents an exception raised from Python.
It has three fields tref
, vref
, bref
which are all PyRef
s, and are the type, value and backtrace of the exception.