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)
source

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.

source
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.

source
PythonCall.@pygMacro
@pyg `...` [var=val, ...]

Execute the given Python code in the global scope.

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

source
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.

source
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()`.

source

Python functions

Construct Python objects

These functions convert Julia values into Python objects of standard types.

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.

source
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.

source
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.

source
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.

source
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.

source
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.

source
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.

source
PythonCall.pysliceFunction
pyslice([T=PyObject,] [start,] stop, [step]) :: T

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

source
PythonCall.pytypeFunction
pytype([T=PyObject,] x) :: T

Equivalent to type(x) in Python.

source
pytype([T=PyObject,] name, bases, dict) :: T

Equivalent to type(name, bases, dict) in Python.

source

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.

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

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

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

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

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

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

source

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.

source
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.

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

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

source
PythonCall.pytruthFunction
pytruth(x) :: Bool

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

source

Numbers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

source

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.

source
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.

source
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.

source
PythonCall.PyIterableType
PyIterable{T=PyObject}(o)

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

source
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].

source
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.
source
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.

source
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.
source
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.

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

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

Suitable for passing to Python's exec function.

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

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

Suitable for passing to Python's eval function.

source
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.

source
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.

source