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.PyObjectType
PyObject(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 PyObjects), comparisons to other PyObjects (x == y), and arithmetic with other PyObjects and Numbers (x + y, x * 3).

Note that comparisons between PyObjects (==, , , 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) is pyconvert(T, x)
  • x.jl!i is pyconvert(Int, x)
  • x.jl!b is pytruth(x)
  • x.jl!s is pystr(String, x).
  • x.jl!r is pyrepr(String, x).
  • x.jl!f is pyconvert(Float64, x)
  • x.jl!c is pyconvert(Complex{Float64}, x)
  • x.jl!iter(T=PyObject) is PyIterable{T}(x)
  • x.jl!list(T=PyObject) is PyList{T}(x)
  • x.jl!set(T=PyObject) is PySet{T}(x)
  • x.jl!dict(K=PyObject, V=PyObject) is PyDict{K,V}(x)
  • x.jl!io(...) is PyIO(x; ...)
  • x.jl!pandasdf(...) is PyPandasDataFrame(x; ...)
  • x.jl!buffer(...) is PyBuffer(x, ...)
  • x.jl!array(...) is PyArray{...}(x)
  • x.jl!vector(...) is PyVector{...}(x)
  • x.jl!matrix(...) is PyMatrix{...}(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.@pyMacro
@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.@pyvMacro
@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.@pygMacro
@pyg `...` [var=val, ...]

Execute the given Python code in the global scope.

This is simply shorthand for @py `...` pyglobals (see @py).

PythonCall.@pyaMacro
@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.@pyrMacro
@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.pyboolFunction
pybool([T=PyObject,] ...) :: T

Equivalent to bool(...) in Python.

PythonCall.pyintFunction
pyint([T=PyObject,] ...) :: T

Equivalent to int(...) in Python.

PythonCall.pyfloatFunction
pyfloat([T=PyObject,] ...) :: T

Equivalent to float(...) in Python.

PythonCall.pystrFunction
pystr([T=PyObject,] x) :: T

Equivalent to str(x) in Python.

PythonCall.pybytesFunction
pybytes([T=PyObject,] x) :: T

Equivalent to str(x) in Python.

PythonCall.pytupleFunction
pytuple([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.pylistFunction
pylist([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.pycollistFunction
pycollist([T=PyObject,] x::AbstractArray) :: T

Create a nested Python list-of-lists from the elements of x. For matrices, this is a list of columns.

PythonCall.pyrowlistFunction
pyrowlist([T=PyObject,] x::AbstractArray) :: T

Create a nested Python list-of-lists from the elements of x. For matrices, this is a list of rows.

PythonCall.pysetFunction
pyset([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.pyfrozensetFunction
pyfrozenset([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.pydictFunction
pydict([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.pysliceFunction
pyslice([T=PyObject,] [start,] stop, [step]) :: T

Equivalent to slice(start, stop, step) in Python (or start:stop:step while indexing).

PythonCall.pyellipsisFunction
pyellipsis([T=PyObject]) :: T

Equivalent to Ellipsis in Python (or ... while indexing).

PythonCall.pymethodFunction
pymethod([T=PyObject,] x) :: T

Convert x to a Python instance method.

PythonCall.pytypeFunction
pytype([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.pyjlFunction
pyjl([T=PyObject,] x)

Wrap x as a Python juliacall.AnyValue (or subclass) object.

PythonCall.pyjlrawFunction
pyjlraw([T=PyObject,] x)

Wrap x as a Python juliacall.RawValue object.

PythonCall.pytextioFunction
pytextio([T=PyObject], io::IO) :: T

Convert io to a Python text IO stream, specifically a juliacall.TextIOValue.

PythonCall.pyrawioFunction
pyrawio([T=PyObject], io::IO) :: T

Convert io to a Python raw (unbuffered byte) IO stream, specifically a juliacall.RawIOValue.

PythonCall.pybufferedioFunction
pybufferedio([T=PyObject], io::IO) :: T

Convert io to a Python buffered byte IO stream, specifically a juliacall.BufferedIOValue.

Python builtins

PythonCall.pyimportFunction
pyimport([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.pywithFunction
pywith(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.pyisFunction
pyis(x, y) :: Bool

Equivalent to x is y in Python.

PythonCall.pyreprFunction
pyrepr([T=PyObject,] x) :: T

Equivalent to repr(x) in Python.

PythonCall.pyhasattrFunction
pyhasattr(x, k) :: Bool

Equivalent to hasattr(x, k) in Python, returned as a Bool.

PythonCall.pygetattrFunction
pygetattr([T=PyObject,] x, k) :: T

Equivalent to x.k or getattr(x, k) in Python.

PythonCall.pysetattrFunction
pysetattr(x, k, v)

Equivalent to x.k = v or setattr(x, k, v) in Python, but returns x.

PythonCall.pydirFunction
pydir([T=PyObject,] x) :: T

Equivalent to dir(x) in Python.

PythonCall.pycallFunction
pycall([T=PyObject,] f, args...; kwargs...) :: T

Equivalent to f(*args, **kwargs) in Python.

PythonCall.pyinFunction
pyin(v, x) :: Bool

Equivalent to v in x in Python.

PythonCall.pygetitemFunction
pygetitem([T=PyObject,] x, k) :: T

Equivalent to x[k] or getitem(x, k) in Python.

PythonCall.pysetitemFunction
pysetitem(x, k, v)

Equivalent to x[k] = v or setitem(x, k, v) in Python, but returns x.

PythonCall.pydelitemFunction
pydelitem(x, k)

Equivalent to del x[k] or delitem(x, k) in Python, but returns x.

PythonCall.pytruthFunction
pytruth(x) :: Bool

The truthyness of x, equivalent to bool(x) or not not x in Python, or to pybool(Bool, x).

PythonCall.pyiterFunction
pyiter([T=PyObject] x) :: T

Equivalent to iter(x) in Python.

Numbers

PythonCall.pyeqFunction
pyeq([T=PyObject,] x, y) :: T

Equivalent to x == y in Python.

PythonCall.pyneFunction
pyne([T=PyObject,] x, y) :: T

Equivalent to x != y in Python.

PythonCall.pyleFunction
pyle([T=PyObject,] x, y) :: T

Equivalent to x <= y in Python.

PythonCall.pyltFunction
pylt([T=PyObject,] x, y) :: T

Equivalent to x < y in Python.

PythonCall.pygeFunction
pyge([T=PyObject,] x, y) :: T

Equivalent to x >= y in Python.

PythonCall.pygtFunction
pygt([T=PyObject,] x, y) :: T

Equivalent to x > y in Python.

PythonCall.pyaddFunction
pyadd([T=PyObject,] x, y) :: T

Equivalent to x + y in Python.

PythonCall.pyiaddFunction
pyiadd([T=typeof(x),] x, y) :: T

x = pyiadd(x, y) is equivalent to x += y in Python.

PythonCall.pysubFunction
pysub([T=PyObject,] x, y) :: T

Equivalent to x - y in Python.

PythonCall.pyisubFunction
pyisub([T=typeof(x),] x, y) :: T

x = pyisub(x, y) is equivalent to x -= y in Python.

PythonCall.pymulFunction
pymul([T=PyObject,] x, y) :: T

Equivalent to x * y in Python.

PythonCall.pyimulFunction
pyimul([T=typeof(x),] x, y) :: T

x = pyimul(x, y) is equivalent to x *= y in Python.

PythonCall.pymatmulFunction
pymatmul([T=PyObject,] x, y) :: T

Equivalent to x @ y in Python.

PythonCall.pyimatmulFunction
pyimatmul([T=typeof(x),] x, y) :: T

x = pyimatmul(x, y) is equivalent to x @= y in Python.

PythonCall.pyifloordivFunction
pyifloordiv([T=typeof(x),] x, y) :: T

x = pyifloordiv(x, y) is equivalent to x //= y in Python.

PythonCall.pyitruedivFunction
pyitruediv([T=typeof(x),] x, y) :: T

x = pyitruediv(x, y) is equivalent to x /= y in Python.

PythonCall.pymodFunction
pymod([T=PyObject,] x, y) :: T

Equivalent to x % y in Python.

PythonCall.pyimodFunction
pyimod([T=typeof(x),] x, y) :: T

x = pyimod(x, y) is equivalent to x %= y in Python.

PythonCall.pydivmodFunction
pydivmod([T=PyObject,] x, y) :: T

Equivalent to divmod(x, y) in Python.

PythonCall.pylshiftFunction
pylshift([T=PyObject,] x, y) :: T

Equivalent to x << y in Python.

PythonCall.pyilshiftFunction
pyilshift([T=typeof(x),] x, y) :: T

x = pyilshift(x, y) is equivalent to x <<= y in Python.

PythonCall.pyrshiftFunction
pyrshift([T=PyObject,] x, y) :: T

Equivalent to x >> y in Python.

PythonCall.pyirshiftFunction
pyirshift([T=typeof(x),] x, y) :: T

x = pyirshift(x, y) is equivalent to x >>= y in Python.

PythonCall.pyandFunction
pyand([T=PyObject,] x, y) :: T

Equivalent to x & y in Python.

PythonCall.pyiandFunction
pyiand([T=typeof(x),] x, y) :: T

x = pyiand(x, y) is equivalent to x &= y in Python.

PythonCall.pyorFunction
pyor([T=PyObject,] x, y) :: T

Equivalent to x | y in Python.

PythonCall.pyiorFunction
pyior([T=typeof(x),] x, y) :: T

x = pyior(x, y) is equivalent to x |= y in Python.

PythonCall.pyxorFunction
pyxor([T=PyObject,] x, y) :: T

Equivalent to x ^ y in Python.

PythonCall.pyixorFunction
pyixor([T=typeof(x),] x, y) :: T

x = pyixor(x, y) is equivalent to x ^= y in Python.

PythonCall.pypowFunction
pypow([T=PyObject,] x, y, [z]) :: T

Equivalent to x**y or pow(x, y, z) in Python.

PythonCall.pyipowFunction
pyipow([T=typeof(x),] x, y, [z]) :: T

x = pyipow(x, y) is equivalent to x **= y in Python.

PythonCall.pynegFunction
pyneg([T=typeof(x),] x) :: T

Equivalent to -x in Python.

PythonCall.pyposFunction
pypos([T=typeof(x),] x) :: T

Equivalent to +x in Python.

PythonCall.pyabsFunction
pyabs([T=typeof(x),] x) :: T

Equivalent to abs(x) in Python.

PythonCall.pyinvFunction
pyinv([T=typeof(x),] x) :: T

Equivalent to -x in Python.

Wrapper types

PythonCall.PyListType
PyList{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.PySetType
PySet{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.PyDictType
PyDict{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.PyIterableType
PyIterable{T=PyObject}(o)

Wrap the Python object o into a Julia object which iterates values of type T.

PythonCall.PyArrayType
PyArray{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.PyBufferType
PyBuffer(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 (usually o).
  • 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.PyIOType
PyIO(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.PyPandasDataFrameType
PyPandasDataFrame(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 be nothing to exclude the index.
  • columntypes: An iterable of columnname=>type or [columnnames...]=>type pairs, used when converting to a table.
  • copy: True to copy columns on conversion.
PythonCall.PyCodeType
PyCode(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.

See also @py_cmd and @pyv_cmd.

PythonCall.@py_cmdMacro
py`...` :: PyCode

Literal syntax for a compiled PyCode object in "exec" mode.

Suitable for passing to Python's exec function.

PythonCall.@pyv_cmdMacro
pyv`...` :: PyCode

Literal syntax for a compiled PyCode object in "eval" mode.

Suitable for passing to Python's eval function.

PythonCall.PyInternedStringType
PyInternedString(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_strMacro
pystr"..." :: PyInternedString

Literal syntax for an interned Python string.

PythonCall.PyExceptionType
PyException <: Exception

Represents an exception raised from Python.

It has three fields tref, vref, bref which are all PyRefs, and are the type, value and backtrace of the exception.